<template>
  <div class="query-sql">
    <!-- 顶部工具栏 -->
    <div class="toolbar">
      <div class="database-select">
        <el-select
          v-model="selectedDatabase"
          placeholder="请选择数据库实例"
          style="width: 400px"
          @change="handleDatabaseChange"
        >
          <el-option
            v-for="db in databases"
            :key="db.id"
            :label="getDatabaseDisplayText(db)"
            :value="db.id"
          >
            <div class="database-option">
              <div class="db-info">
                <span class="db-name">{{ db.name }}</span>
                <span class="db-detail">
                  {{ db.host }}:{{ db.port }}/{{ db.database_name || '(服务器连接)' }}
                </span>
                <span v-if="!db.database_name" class="db-info-text">
                  📋 右键选择数据库
                </span>
              </div>
              <div class="db-option-actions">
                <el-tag :type="getDbTypeTag(db.database_type)" size="small">
                  {{ db.database_type.toUpperCase() }}
                </el-tag>
                <el-button
                  size="small"
                  type="danger"
                  text
                  class="delete-btn"
                  @click.stop="deleteConnectionFromDropdown(db.id, db.name)"
                  title="删除连接"
                >
                  🗑️
                </el-button>
              </div>
            </div>
          </el-option>
        </el-select>

        <!-- 当前数据库上下文显示 -->
        <div v-if="currentDatabaseContext" class="current-database-context">
          <el-tag type="success" size="small">
            <el-icon><Database /></el-icon>
            当前数据库: {{ currentDatabaseContext }}
          </el-tag>
        </div>
      </div>

      <div class="toolbar-actions">
        <el-button type="primary" @click="showAddConnectionDialog">
          <el-icon><Plus /></el-icon>
          新建连接
        </el-button>
      </div>
    </div>

    <!-- 主要内容区域：左右分栏 -->
    <div class="main-content">
      <!-- 左侧表结构面板 (1/3) -->
      <div class="left-panel" v-show="!leftPanelCollapsed">
        <div class="panel-header">
          <h3>数据库结构</h3>
        </div>

        <!-- 数据库树形结构 -->
        <div class="database-tree-container" v-if="selectedDatabase">
          <!-- 搜索框 -->
          <div class="tree-search">
            <el-input
              v-model="searchText"
              placeholder="搜索数据库或表..."
              :prefix-icon="Search"
              size="small"
              clearable
            />
          </div>

          <!-- 树形结构 -->
          <div
            class="tree-content"
            :style="selectedTable && tableColumns.length > 0 ? { height: treeContentHeight + 'px' } : {}"
          >
            <div v-if="loadingTree" class="loading-state">
              <el-icon class="is-loading"><Loading /></el-icon>
              <span>加载数据库结构中...</span>
            </div>

            <el-tree
              v-else
              ref="treeRef"
              :key="`tree-${selectedDatabase}`"
              :data="treeData"
              :props="treeProps"
              :expand-on-click-node="false"
              :default-expanded-keys="expandedKeys"
              node-key="id"
              lazy
              :load="loadTreeNode"
              :filter-node-method="filterNode"
              @node-click="handleNodeClick"
              @node-contextmenu="handleNodeRightClick"
            >
              <template #default="{ node, data }">
                <div class="tree-node">
                  <el-icon v-if="data.type === 'instance'">
                    <Connection />
                  </el-icon>
                  <el-icon v-else-if="data.type === 'database'">
                    <Database />
                  </el-icon>
                  <el-icon v-else-if="data.type === 'table'">
                    <Document />
                  </el-icon>
                  <span class="node-label">{{ data.label }}</span>
                  <span v-if="data.type === 'table' && data.rows" class="table-rows">
                    {{ data.rows }} 行
                  </span>
                </div>
              </template>
            </el-tree>

            <div v-if="!loadingTree && treeData.length === 0" class="empty-state">
              <el-icon><Database /></el-icon>
              <p>暂无数据库连接</p>
              <p class="empty-tip">请先在顶部选择数据库实例</p>
            </div>
          </div>

          <!-- 水平拖动分隔条 -->
          <div
            v-if="selectedTable && tableColumns.length > 0"
            class="horizontal-resize-handle"
            @mousedown="startHorizontalResize"
            title="拖动调整数据库树和字段列表的比例"
          >
            <div class="horizontal-resize-line"></div>
          </div>

          <!-- 选中表的字段信息 -->
          <div v-if="selectedTable && tableColumns.length > 0" class="columns-section">
            <div class="section-title">
              <el-icon><List /></el-icon>
              <span>字段 ({{ tableColumns.length }})</span>
            </div>
            <div class="columns-list">
              <div
                v-for="column in tableColumns"
                :key="column.name"
                class="column-item"
                @dblclick="insertColumnName(column.name)"
              >
                <div class="column-info">
                  <span class="column-name">{{ column.name }}</span>
                  <span class="column-type">{{ column.type }}</span>
                </div>
                <div class="column-attrs">
                  <el-tag v-if="column.key === 'PRI'" type="danger" size="small">主键</el-tag>
                  <el-tag v-if="column.null === 'NO'" type="warning" size="small">非空</el-tag>
                  <el-tag v-if="column.extra === 'auto_increment'" type="info" size="small">自增</el-tag>
                </div>
              </div>
            </div>
          </div>

          <!-- 右键菜单 -->
          <div
            v-if="contextMenuVisible"
            class="context-menu"
            :style="{
              position: 'fixed',
              left: contextMenuPosition.x + 'px',
              top: contextMenuPosition.y + 'px',
              zIndex: 9999
            }"
          >
            <!-- 数据库级别菜单 -->
            <div v-if="contextMenuData?.type === 'database'" class="menu-group">
              <div class="menu-item" @click="contextMenuActions.connectToDatabase(contextMenuData)">
                <el-icon><Connection /></el-icon>
                <span>连接到此数据库</span>
              </div>
              <div class="menu-item" @click="contextMenuActions.refreshDatabase(contextMenuData)">
                <el-icon><Refresh /></el-icon>
                <span>刷新数据库</span>
              </div>
              <div class="menu-item" @click="contextMenuActions.showDatabaseInfo(contextMenuData)">
                <el-icon><View /></el-icon>
                <span>查看数据库信息</span>
              </div>
            </div>

            <!-- 表级别菜单 -->
            <div v-if="contextMenuData?.type === 'table'" class="menu-group">
              <div class="menu-item" @click="contextMenuActions.selectFromTable(contextMenuData)">
                <el-icon><Search /></el-icon>
                <span>SELECT查询</span>
              </div>
              <div class="menu-item" @click="contextMenuActions.showTableStructure(contextMenuData)">
                <el-icon><List /></el-icon>
                <span>查看表结构</span>
              </div>
              <div class="menu-divider"></div>
              <div class="menu-item" @click="contextMenuActions.insertIntoTable(contextMenuData)">
                <el-icon><DocumentAdd /></el-icon>
                <span>插入数据</span>
              </div>
              <div class="menu-item" @click="contextMenuActions.updateTable(contextMenuData)">
                <el-icon><Edit /></el-icon>
                <span>更新数据</span>
              </div>
            </div>
          </div>
        </div>

        <div v-else class="no-database">
          <el-icon><Database /></el-icon>
          <p>请选择数据库实例</p>
        </div>
      </div>

      <!-- 右侧SQL编辑器面板 (2/3) -->
      <div class="right-panel">
        <div class="panel-header">
          <div class="panel-title">
            <el-button
              class="collapse-btn"
              size="small"
              :icon="leftPanelCollapsed ? ArrowRight : ArrowLeft"
              @click="toggleLeftPanel"
              :title="leftPanelCollapsed ? '展开数据库结构' : '收起数据库结构'"
            />
            <h3>SQL编辑器</h3>
          </div>
          <div class="editor-actions">
            <el-button
              class="new-query-btn"
              size="default"
              @click="newQuery"
              :icon="DocumentAdd"
            >
              新建查询
            </el-button>
            <el-button
              v-if="sqlPermissionCheck.canExecute"
              class="execute-query-btn"
              type="primary"
              size="default"
              @click="executeQuery"
              :loading="executing"
              :disabled="!selectedDatabase || !currentTabSqlContent"
              :icon="CaretRight"
            >
              执行查询
            </el-button>
            <el-button
              v-else
              class="submit-workorder-btn"
              type="warning"
              size="default"
              @click="showWorkOrderDialog = true"
              :disabled="!selectedDatabase || !currentTabSqlContent"
              :icon="DocumentAdd"
            >
              提交工单
            </el-button>
          </div>
        </div>

        <!-- SQL权限状态提示栏 -->
        <div class="sql-status-bar" :class="sqlPermissionCheck.statusType">
          <div class="status-indicator">
            <el-icon :color="sqlPermissionCheck.statusColor">
              <component :is="sqlPermissionCheck.statusIcon" />
            </el-icon>
            <span :style="{ color: sqlPermissionCheck.statusColor }">
              {{ sqlPermissionCheck.statusText }}
            </span>
          </div>

          <div class="user-info">
            <el-tag v-if="isAdmin" type="warning" size="small">管理员</el-tag>
            <el-icon><User /></el-icon>
            <span>{{ userInfo.username }}</span>
          </div>
        </div>

        <!-- 提示信息 -->
        <div v-if="sqlPermissionCheck.tip" class="status-tip">
          💡 {{ sqlPermissionCheck.tip }}
        </div>

        <!-- 查询标签页 -->
        <div class="query-tabs">
          <el-tabs
            v-model="activeTabName"
            type="card"
            closable
            @tab-remove="removeTab"
            @tab-click="handleTabClick"
          >
            <el-tab-pane
              v-for="tab in queryTabs"
              :key="tab.name"
              :label="tab.title"
              :name="tab.name"
              :closable="tab.closable"
            >
              <!-- SQL编辑器 -->
              <div class="sql-editor-container">
                <SimpleSQLEditor
                  v-model="tab.sqlContent"
                  :placeholder="`-- 请输入SQL查询语句...
-- 标签页: ${tab.title}
-- 数据库: ${getCurrentDatabaseName()}`"
                  @change="handleSqlContentChange"
                  @ready="handleEditorReady"
                  :key="`editor-${tab.name}`"
                />
              </div>

              <!-- 查询结果 -->
              <div class="query-results">
                <!-- 单个结果显示 -->
                <div v-if="tab.result && !tab.multiResults" class="result-content">
                  <div class="result-header">
                    <h4>查询结果</h4>
                    <div class="result-actions">
                      <el-tag v-if="tab.result.sqlType" :type="getSqlTypeTag(tab.result.sqlType)" size="small">
                        {{ tab.result.sqlType }}
                      </el-tag>
                      <el-button size="small" @click="exportResults(tab.result)">
                        <el-icon><Download /></el-icon>
                        导出
                      </el-button>
                    </div>
                  </div>

                  <div v-if="tab.result.columns && tab.result.rows" class="result-table">
                    <el-table
                      :data="tab.result.rows"
                      border
                      stripe
                      size="small"
                      style="width: 100%"
                      :show-overflow-tooltip="false"
                      :flexible="true"
                    >
                      <el-table-column
                        v-for="(column, index) in tab.result.columns"
                        :key="index"
                        :prop="index.toString()"
                        :label="column"
                        min-width="120"
                        show-overflow-tooltip
                      >
                        <template #default="scope">
                          {{ scope.row[index] }}
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>

                  <div v-else-if="tab.result.sqlType !== 'SELECT'" class="non-select-result">
                    <el-alert
                      :title="tab.result.message || `${tab.result.sqlType}语句执行成功`"
                      type="success"
                      show-icon
                      :closable="false"
                    />
                  </div>

                  <div class="result-footer">
                    <span>执行时间: {{ tab.result.execution_time }}ms</span>
                    <span>影响行数: {{ tab.result.rows_affected || tab.result.rows?.length || 0 }}</span>
                    <span v-if="tab.result.rows">实际数据行数: {{ tab.result.rows?.length || 0 }}</span>
                  </div>
                </div>

                <!-- 多结果集显示 -->
                <div v-else-if="tab.multiResults && tab.multiResults.length > 0" class="multi-results-content">
                  <div class="multi-results-header">
                    <h4>查询结果 ({{ tab.multiResults.length }}条语句)</h4>
                  </div>

                  <el-tabs type="border-card" class="result-tabs">
                    <el-tab-pane
                      v-for="(result, index) in tab.multiResults"
                      :key="result.id"
                      :label="getResultTabLabel(result, index)"
                    >
                      <!-- 错误结果 -->
                      <div v-if="result.error" class="error-result">
                        <el-alert
                          :title="result.error"
                          type="error"
                          show-icon
                          :closable="false"
                        />

                      </div>

                      <!-- 成功结果 -->
                      <div v-else class="success-result">
                        <div class="result-header">
                          <div class="result-info">
                            <el-tag :type="getSqlTypeTag(result.sqlType)" size="small">
                              {{ result.sqlType }}
                            </el-tag>
                            <span v-if="result.tableName" class="table-name">表: {{ result.tableName }}</span>
                          </div>
                          <el-button size="small" @click="exportResults(result)">
                            <el-icon><Download /></el-icon>
                            导出
                          </el-button>
                        </div>

                        <!-- SELECT结果表格 -->
                        <div v-if="result.columns && result.rows" class="result-table">
                          <el-table
                            :data="result.rows"
                            border
                            stripe
                            size="small"
                            style="width: 100%"
                            :show-overflow-tooltip="false"
                            :flexible="true"
                          >
                            <el-table-column
                              v-for="(column, colIndex) in result.columns"
                              :key="colIndex"
                              :prop="colIndex.toString()"
                              :label="column"
                              min-width="120"
                              show-overflow-tooltip
                            >
                              <template #default="scope">
                                {{ scope.row[colIndex] }}
                              </template>
                            </el-table-column>
                          </el-table>
                        </div>

                        <!-- 非SELECT结果 -->
                        <div v-else class="non-select-result">
                          <el-alert
                            :title="result.message || `${result.sqlType}语句执行成功`"
                            type="success"
                            show-icon
                            :closable="false"
                          />
                        </div>

                        <div class="result-footer">
                          <span>执行时间: {{ result.execution_time }}ms</span>
                          <span>影响行数: {{ result.rows_affected || result.rows?.length || 0 }}</span>
                          <span v-if="result.rows">实际数据行数: {{ result.rows?.length || 0 }}</span>
                        </div>


                      </div>
                    </el-tab-pane>
                  </el-tabs>
                </div>

                <!-- 错误显示 -->
                <div v-else-if="tab.error" class="error-content">
                  <el-alert
                    :title="tab.error"
                    type="error"
                    show-icon
                    :closable="false"
                  />
                </div>

                <!-- 空结果 -->
                <div v-else class="empty-result">
                  <el-icon><Document /></el-icon>
                  <p>请执行SQL查询以查看结果</p>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>


      </div>
    </div>

    <!-- 新建/编辑数据库连接对话框 -->
    <el-dialog
      v-model="addConnectionDialogVisible"
      :title="editMode ? '编辑数据库连接' : '新建数据库连接'"
      width="600px"
      :close-on-click-modal="false"
      @opened="onDialogOpened"
      @closed="onDialogClosed"
    >
      <el-form
        ref="connectionFormRef"
        :model="connectionForm"
        :rules="connectionRules"
        label-width="120px"
        label-position="left"
      >
        <el-form-item label="连接名称" prop="name">
          <el-input
            v-model="connectionForm.name"
            placeholder="请输入连接名称，如：生产环境MySQL"
          />
        </el-form-item>

        <el-form-item label="数据库类型" prop="database_type">
          <el-select
            v-model="connectionForm.database_type"
            placeholder="请选择数据库类型"
            style="width: 100%"
            @change="handleDatabaseTypeChange"
          >
            <el-option label="MySQL" value="mysql" />
            <el-option label="PostgreSQL" value="postgresql" />
            <el-option label="SQLite" value="sqlite" />
            <el-option label="Oracle" value="oracle" />
            <el-option label="SQL Server" value="sqlserver" />
            <el-option label="MongoDB" value="mongodb" />
          </el-select>
        </el-form-item>

        <el-form-item label="端口" prop="port">
          <el-input
            v-model.number="connectionForm.port"
            :key="`port-${connectionForm.database_type}-${connectionForm.port}`"
            type="number"
            min="0"
            max="65535"
            style="width: 200px"
            placeholder="端口号"
          />
          <div class="port-hint">
            <span style="font-size: 12px; color: #909399;">
              {{ connectionForm.database_type ? `${connectionForm.database_type.toUpperCase()}默认端口: ${defaultPorts[connectionForm.database_type] || 3306}` : '' }}
            </span>
          </div>
        </el-form-item>

        <el-form-item label="服务器地址" prop="host">
          <el-input
            v-model="connectionForm.host"
            placeholder="如：192.168.1.100"
          />
        </el-form-item>

        <el-form-item
          :label="getDatabaseNameLabel()"
          prop="database_name"
          :rules="getDatabaseNameRules()"
        >
          <el-input
            v-model="connectionForm.database_name"
            :placeholder="getDatabaseNamePlaceholder()"
          />
          <div class="database-name-hint" v-if="getDatabaseNameHint()">
            <span style="font-size: 12px; color: #909399;">
              {{ getDatabaseNameHint() }}
            </span>
          </div>
        </el-form-item>

        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="connectionForm.username"
            placeholder="请输入用户名"
          />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="connectionForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="描述">
          <el-input
            v-model="connectionForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入连接描述（可选）"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addConnectionDialogVisible = false">取消</el-button>
          <el-button @click="testConnectionBeforeSave" :loading="testingConnection">
            测试连接
          </el-button>
          <el-button type="primary" @click="saveConnection" :loading="savingConnection">
            {{ editMode ? '更新连接' : '保存连接' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 工单提交对话框 -->
    <el-dialog
      v-model="showWorkOrderDialog"
      title="提交SQL工单"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="workOrderForm" label-width="100px">
        <el-form-item label="工单标题" required>
          <el-input
            v-model="workOrderForm.title"
            placeholder="请输入工单标题"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="数据库实例">
          <el-input :value="getCurrentDatabase()?.name" disabled />
        </el-form-item>

        <el-form-item label="SQL内容">
          <el-input
            type="textarea"
            :rows="6"
            v-model="workOrderForm.sql_content"
            disabled
          />
        </el-form-item>

        <el-form-item label="申请原因" required>
          <el-input
            type="textarea"
            :rows="4"
            v-model="workOrderForm.description"
            placeholder="请详细说明SQL执行的原因和目的"
            maxlength="1000"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="指定审核人">
          <!-- 审核人选择范围提示 -->
          <div class="reviewer-scope-tip" style="margin-bottom: 8px;">
            <el-alert
              v-if="reviewerInfo.userInGroup"
              :title="`您当前在 [${reviewerInfo.groupNames.join(', ')}] 组中，只能选择组内成员作为审核人 (共${reviewerInfo.totalCount}人)`"
              type="info"
              :closable="false"
              size="small"
            />
            <el-alert
              v-else
              :title="`您可以选择任意有审核权限的用户作为审核人 (共${reviewerInfo.totalCount}人)`"
              type="success"
              :closable="false"
              size="small"
            />
          </div>

          <el-select
            v-model="workOrderForm.reviewer"
            placeholder="请选择审核人"
            style="width: 100%"
            filterable
            remote
            :remote-method="filterReviewers"
            :loading="false"
          >
            <el-option
              v-for="admin in adminUsers"
              :key="admin.id"
              :label="formatUsernameForOption(admin)"
              :value="admin.id"
            >
              <div style="display: flex; justify-content: space-between; align-items: center;">
                <UserDisplay :user="admin" />
                <span style="color: #8492a6; font-size: 12px;">
                  {{ admin.first_name || admin.username }}
                </span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="优先级">
          <el-select v-model="workOrderForm.priority" style="width: 100%">
            <el-option label="低" value="low" />
            <el-option label="普通" value="normal" />
            <el-option label="高" value="high" />
            <el-option label="紧急" value="urgent" />
          </el-select>
        </el-form-item>

        <el-form-item label="预期执行时间">
          <el-date-picker
            v-model="workOrderForm.expected_execution_time"
            type="datetime"
            placeholder="选择预期执行时间"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showWorkOrderDialog = false">取消</el-button>
          <el-button type="primary" @click="submitWorkOrder">提交工单</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Link, Plus, Refresh, Document, CaretRight, Download,
  Files, List, Loading, Coin as Database, Edit, Delete, Close,
  DeleteFilled, RemoveFilled, CircleClose, FolderOpened, Folder,
  Search, Connection, View, DocumentAdd, ArrowLeft, ArrowRight, Warning, User
} from '@element-plus/icons-vue'
import { sqlAPI } from '@/api/sql'
import { sqlWorkOrderAPI } from '@/api/sqlWorkOrder'
import SimpleSQLEditor from '@/components/SimpleSQLEditor.vue'
import UserDisplay from '@/components/UserDisplay.vue'
import { formatUsername } from '@/utils/userUtils'

// 响应式数据
const queryForm = ref({
  sql_content: ''
})

const databases = ref([])
const selectedDatabase = ref(null)
const executing = ref(false)
const queryResult = ref(null)
const currentPage = ref(1)
const pageSize = ref(100)

// 左侧面板折叠状态
const leftPanelCollapsed = ref(false)

// 左侧面板高度控制
const treeContentHeight = ref(400)
const isResizing = ref(false)
const treeContentRef = ref(null)

// 用户权限相关
const userInfo = ref({})
const adminUsers = ref([])
const filteredAdminUsers = ref([])
const showWorkOrderDialog = ref(false)
const reviewerInfo = ref({
  userInGroup: false,
  groupNames: [],
  totalCount: 0
})

// 工单表单
const workOrderForm = reactive({
  title: '',
  description: '',
  sql_content: '',
  request_type: 'dml',
  database_instance: null,
  reviewer: null,
  priority: 'normal',
  expected_execution_time: null
})

// 多标签页相关
const queryTabs = ref([
  {
    name: 'tab-1',
    title: '查询1',
    sqlContent: '',
    result: null,
    error: null,
    closable: false
  }
])
const activeTabName = ref('tab-1')
const tabCounter = ref(1)

// Monaco Editor相关
const monacoEditorRefs = ref({})

// 数据库连接状态
const connectedDatabase = ref(null) // 当前连接的数据库名称

// 表结构相关
const loadingTables = ref(false)
const tables = ref([])
const selectedTable = ref(null)
const tableColumns = ref([])

// 树形结构相关
const treeData = ref([])
const loadingTree = ref(false)
const expandedKeys = ref([])
const searchText = ref('')
const currentDatabaseContext = ref(null) // 当前查询上下文的数据库
const treeRef = ref(null)

// 数据库浏览器相关
const databaseList = ref([]) // 数据库实例下的数据库列表
const contextMenuVisible = ref(false)
const contextMenuPosition = ref({ x: 0, y: 0 })
const contextMenuData = ref(null) // 右键菜单的目标数据

// 新建连接相关
const addConnectionDialogVisible = ref(false)
const connectionFormRef = ref(null)
const editMode = ref(false) // 编辑模式标识
const connectionForm = ref({
  name: '',
  database_type: 'mysql',
  host: 'localhost',
  port: 3306,
  database_name: '',
  username: '',
  password: '',
  description: ''
})
const savingConnection = ref(false)
const testingConnection = ref(false)

// 表单验证规则
const connectionRules = {
  name: [
    { required: true, message: '请输入连接名称', trigger: 'blur' }
  ],
  database_type: [
    { required: true, message: '请选择数据库类型', trigger: 'change' }
  ],
  host: [
    { required: true, message: '请输入服务器地址', trigger: 'blur' }
  ],
  port: [
    { required: true, message: '请输入端口号', trigger: 'blur' },
    { type: 'number', min: 0, max: 65535, message: '端口号必须在 0-65535 之间', trigger: 'blur' }
  ],
  // database_name 验证规则现在通过 getDatabaseNameRules() 动态生成
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

// 端口映射配置
const defaultPorts = {
  mysql: 3306,
  postgresql: 5432,
  sqlite: 0,
  oracle: 1521,
  sqlserver: 1433,
  mongodb: 27017
}

// 数据库类型配置
const databaseTypeConfig = {
  mysql: {
    required: false,
    placeholder: '请输入数据库名称（可选）',
    hint: '可选项：可以只连接服务器后再选择具体数据库',
    defaultValue: '',
    label: '数据库名称'
  },
  postgresql: {
    required: false,
    placeholder: '如：postgres',
    hint: '可选项：建议填写默认数据库名"postgres"',
    defaultValue: 'postgres',
    label: '数据库名称'
  },
  sqlite: {
    required: true,
    placeholder: '如：/path/to/database.db',
    hint: '必填项：请填写SQLite文件的完整路径',
    defaultValue: '',
    label: '数据库文件路径'
  },
  oracle: {
    required: true,
    placeholder: '如：ORCL 或 localhost:1521/XE',
    hint: '必填项：请填写服务名(Service Name)或SID',
    defaultValue: '',
    label: '服务名/SID'
  },
  sqlserver: {
    required: true,
    placeholder: '如：master',
    hint: '必填项：请填写要连接的数据库名称',
    defaultValue: 'master',
    label: '数据库名称'
  },
  mongodb: {
    required: false,
    placeholder: '请输入数据库名称（可选）',
    hint: '可选项：可以只连接服务器',
    defaultValue: '',
    label: '数据库名称'
  }
}

// 树形结构配置
const treeProps = {
  children: 'children',
  label: 'label',
  isLeaf: 'isLeaf'
}

// 计算属性
const currentTabSqlContent = computed(() => {
  const currentTab = getCurrentTab()
  const content = currentTab?.sqlContent?.trim() || ''
  console.log('当前标签页SQL内容:', content, '长度:', content.length)
  return content
})

// 权限相关计算属性
const isAdmin = computed(() => {
  console.log('检查管理员权限:', userInfo.value)
  return userInfo.value.is_superuser || userInfo.value.is_staff
})

// SQL权限检查
const sqlPermissionCheck = computed(() => {
  const currentTab = getCurrentTab()
  if (!currentTab || !currentTab.sqlContent) {
    return {
      isDangerous: false,
      canExecute: true,
      needWorkOrder: false,
      statusType: 'safe',
      statusIcon: 'Search',
      statusText: '请输入SQL语句',
      statusColor: '#909399'
    }
  }

  const sql = currentTab.sqlContent.trim().toUpperCase()
  const dangerousOps = ['INSERT', 'UPDATE', 'DELETE', 'DROP', 'CREATE', 'ALTER', 'TRUNCATE', 'REPLACE', 'MERGE']

  const isDangerous = dangerousOps.some(op =>
    sql.startsWith(op) || sql.includes(` ${op} `)
  )

  if (!isDangerous) {
    return {
      isDangerous: false,
      canExecute: true,
      needWorkOrder: false,
      statusType: 'safe',
      statusIcon: 'Search',
      statusText: '查询模式 - 安全操作',
      statusColor: '#52c41a'
    }
  }

  if (isAdmin.value) {
    return {
      isDangerous: true,
      canExecute: true,
      needWorkOrder: false,
      statusType: 'admin-dangerous',
      statusIcon: 'Warning',
      statusText: '管理员模式 - 数据修改操作',
      statusColor: '#fa8c16',
      tip: '请谨慎操作，建议先备份'
    }
  }

  return {
    isDangerous: true,
    canExecute: false,
    needWorkOrder: true,
    statusType: 'forbidden',
    statusIcon: 'Close',
    statusText: '权限不足 - 仅允许查询操作',
    statusColor: '#ff4d4f'
  }
})

const paginatedRows = computed(() => {
  if (!queryResult.value?.rows || !Array.isArray(queryResult.value.rows)) {
    console.log('No rows data or not array:', queryResult.value?.rows)
    return []
  }

  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  const slicedData = queryResult.value.rows.slice(start, end)

  console.log('Paginated data:', {
    total: queryResult.value.rows.length,
    start,
    end,
    slicedData: slicedData.slice(0, 2) // 只显示前2行用于调试
  })

  return slicedData
})

// 获取当前数据库
const getCurrentDatabase = () => {
  return databases.value.find(db => db.id === selectedDatabase.value)
}

// 获取当前数据库名称（用于Monaco Editor占位符）
const getCurrentDatabaseName = () => {
  const currentDb = getCurrentDatabase()
  if (!currentDb) return '未选择数据库'

  const dbName = currentDb.database_name || '(服务器连接)'
  return `${currentDb.name} (${currentDb.host}:${currentDb.port}/${dbName})`
}

// 处理SQL内容变化
const handleSqlContentChange = (value) => {
  const currentTab = getCurrentTab()
  if (currentTab) {
    currentTab.sqlContent = value
  }
}

// 处理Monaco Editor就绪事件
const handleEditorReady = (editorInstance) => {
  console.log('Monaco SQL编辑器就绪:', editorInstance)

  // 可以在这里添加额外的编辑器配置
  // 例如：设置自定义主题、添加快捷键等
}

// 获取数据库类型标签
const getDbTypeTag = (type) => {
  const typeMap = {
    mysql: 'success',
    postgresql: 'primary',
    sqlite: 'info',
    oracle: 'warning'
  }
  return typeMap[type.toLowerCase()] || 'info'
}

// 加载数据库列表
const loadDatabases = async () => {
  try {
    const response = await sqlAPI.getDatabaseInstances()
    console.log('API响应:', response)

    // 由于axios拦截器返回response.data，所以直接处理response
    let data = []
    if (response) {
      if (response.results) {
        // 分页响应格式
        data = response.results
      } else if (Array.isArray(response)) {
        // 直接数组格式
        data = response
      } else if (response.data && Array.isArray(response.data)) {
        // 嵌套data格式
        data = response.data
      }
    }

    databases.value = data
    console.log('加载的数据库列表:', databases.value)
  } catch (error) {
    console.error('加载数据库失败:', error)
    ElMessage.error(`加载数据库失败: ${error.response?.data?.error || error.message}`)
  }
}



// 删除数据库连接
const deleteConnection = async (connectionId, connectionName) => {
  if (!connectionId || !connectionName) {
    ElMessage.warning('连接信息不完整')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除连接 '${connectionName}' 吗？此操作不可撤销。`,
      '删除确认',
      {
        type: 'warning',
        confirmButtonText: '确定删除',
        cancelButtonText: '取消'
      }
    )

    // 调用删除API
    await sqlAPI.deleteDatabaseInstance(connectionId)
    ElMessage.success('连接删除成功')

    // 状态清理和刷新
    if (selectedDatabase.value === connectionId) {
      selectedDatabase.value = null
      tables.value = []
      selectedTable.value = null
      tableColumns.value = []
      queryResult.value = null
    }

    // 刷新数据库列表
    await refreshDatabases()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除连接失败:', error)
      const errorMessage = error.response?.data?.error || error.message || '删除连接失败'
      ElMessage.error(errorMessage)
    }
  }
}

// 从下拉框删除数据库连接
const deleteConnectionFromDropdown = async (connectionId, connectionName) => {
  // 调用现有的删除方法
  await deleteConnection(connectionId, connectionName)
}

// 编辑数据库连接
const editConnection = (connection) => {
  if (!connection) {
    ElMessage.warning('连接信息不完整')
    return
  }

  // 预填充表单数据
  connectionForm.value = {
    id: connection.id,
    name: connection.name,
    database_type: connection.database_type,
    host: connection.host,
    port: connection.port,
    database_name: connection.database_name || '',
    username: connection.username,
    password: '', // 出于安全考虑，不预填充密码
    description: connection.description || ''
  }

  editMode.value = true
  addConnectionDialogVisible.value = true
}

// 处理数据库变化
const handleDatabaseChange = async (value) => {
  console.log('数据库实例变化:', value)

  // 重置连接状态
  connectedDatabase.value = null
  currentDatabaseContext.value = null

  // 清空表结构数据
  tables.value = []
  selectedTable.value = null
  tableColumns.value = []

  // 清空树形结构
  treeData.value = []
  expandedKeys.value = []

  // 清空所有标签页的结果
  queryTabs.value.forEach(tab => {
    tab.result = null
    tab.error = null
  })

  // 如果选择了数据库实例，自动加载数据库列表和树形结构
  if (value) {
    selectedDatabase.value = value

    const currentDb = getCurrentDatabase()
    console.log('当前选择的数据库实例:', currentDb)

    if (currentDb) {
      if (currentDb.database_name) {
        // 如果实例已指定数据库名称，直接连接并加载表结构
        connectedDatabase.value = currentDb.database_name
        currentDatabaseContext.value = currentDb.database_name
        console.log('实例已指定数据库，直接连接:', currentDb.database_name)
        await loadTableStructure()
      } else {
        // 如果实例未指定数据库名称，加载数据库列表用于树形结构显示
        console.log('实例未指定数据库，加载数据库列表')
        await loadDatabaseList()
      }
    }
  } else {
    selectedDatabase.value = null
  }
}

// 数据库类型变化时更新默认端口和数据库名称
const handleDatabaseTypeChange = (type) => {
  const newPort = defaultPorts[type] || 3306
  connectionForm.value.port = newPort

  // 根据数据库类型设置默认数据库名称
  const config = databaseTypeConfig[type]
  if (config && config.defaultValue) {
    connectionForm.value.database_name = config.defaultValue
  } else {
    connectionForm.value.database_name = ''
  }

  // 强制更新视图
  nextTick(() => {
    // 确保端口值在界面上正确显示
    if (connectionFormRef.value) {
      connectionFormRef.value.validateField('port')
      connectionFormRef.value.validateField('database_name')
    }
  })
}

// 获取数据库名称字段标签
const getDatabaseNameLabel = () => {
  const config = databaseTypeConfig[connectionForm.value.database_type]
  return config ? config.label : '数据库名称'
}

// 获取数据库名称占位符
const getDatabaseNamePlaceholder = () => {
  const config = databaseTypeConfig[connectionForm.value.database_type]
  return config ? config.placeholder : '请输入数据库名称'
}

// 获取数据库名称提示信息
const getDatabaseNameHint = () => {
  const config = databaseTypeConfig[connectionForm.value.database_type]
  return config ? config.hint : ''
}

// 获取数据库名称验证规则
const getDatabaseNameRules = () => {
  const config = databaseTypeConfig[connectionForm.value.database_type]
  if (config && config.required) {
    return [
      { required: true, message: `请输入${config.label}`, trigger: 'blur' }
    ]
  }
  return [] // 可选字段不需要验证规则
}

// 监听数据库类型变化
watch(
  () => connectionForm.value.database_type,
  (newType) => {
    if (newType) {
      handleDatabaseTypeChange(newType)
    }
  },
  { immediate: true }
)

// 树形结构相关方法
// 懒加载树节点
const loadTreeNode = async (node, resolve) => {
  try {
    console.log('懒加载节点:', node.level, node.data)

    if (node.level === 0) {
      // 根节点，返回空（因为我们直接设置treeData）
      resolve([])
    } else if (node.level === 1 && node.data.type === 'instance') {
      // 实例节点，返回数据库列表（已在buildDatabaseBrowserTree中设置）
      resolve(node.data.children || [])
    } else if (node.level === 2 && node.data.type === 'database') {
      // 数据库节点，检查是否已连接到此数据库才加载表列表
      console.log('尝试加载数据库表列表:', node.data.database, '当前连接的数据库:', connectedDatabase.value)

      if (connectedDatabase.value === node.data.database) {
        console.log('已连接到此数据库，开始加载表列表')
        await loadTableListForDatabase(node.data, resolve)
      } else {
        console.log('未连接到此数据库，不加载表列表')
        resolve([])
      }
    } else {
      resolve([])
    }
  } catch (error) {
    console.error('懒加载节点失败:', error)
    resolve([])
  }
}

// 为指定数据库加载表列表
const loadTableListForDatabase = async (databaseData, resolve) => {
  try {
    const currentDb = getCurrentDatabase()
    if (!currentDb) {
      console.log('没有当前数据库实例')
      resolve([])
      return
    }

    console.log('开始加载数据库表列表:', {
      database: databaseData.database,
      instanceId: selectedDatabase.value,
      connectedDatabase: connectedDatabase.value
    })

    // 使用新的API获取表列表
    const response = await sqlAPI.getTableList(selectedDatabase.value, databaseData.database)
    console.log('表列表API响应:', response)

    if (response && response.tables && Array.isArray(response.tables)) {
      const tableNodes = response.tables.map(table => {
        const tableName = typeof table === 'string' ? table : table.name
        return {
          id: `table_${databaseData.database}_${tableName}`,
          label: tableName,
          type: 'table',
          database: databaseData.database,
          table: tableName,
          instanceId: databaseData.instanceId,
          rows: null, // 可以后续添加行数统计
          isLeaf: true
        }
      })

      console.log(`成功加载 ${tableNodes.length} 个表:`, tableNodes.map(t => t.label))

      if (tableNodes.length > 0) {
        ElMessage.success(`已加载数据库 ${databaseData.database} 中的 ${tableNodes.length} 个表`)
      } else {
        ElMessage.info(`数据库 ${databaseData.database} 中没有表`)
      }

      resolve(tableNodes)
    } else {
      console.log('API响应中没有表数据或格式不正确')
      ElMessage.warning(`数据库 ${databaseData.database} 中没有可访问的表`)
      resolve([])
    }
  } catch (error) {
    console.error('加载表列表失败:', error)

    let errorMessage = `加载数据库 ${databaseData.database} 的表列表失败`
    if (error.response?.data?.error) {
      errorMessage += `: ${error.response.data.error}`
    } else if (error.message) {
      errorMessage += `: ${error.message}`
    }

    ElMessage.error(errorMessage)
    resolve([])
  }
}

// 加载表树（暂时禁用，等待后端API实现）
// const loadTableTree = async (databaseNode, resolve) => {
//   try {
//     const response = await sqlAPI.getTableList(selectedDatabase.value, databaseNode.database)
//     const tables = response.data || response || []

//     const tableNodes = tables.map(table => ({
//       id: `table_${databaseNode.database}_${table.name}`,
//       label: table.name,
//       type: 'table',
//       database: databaseNode.database,
//       table: table.name,
//       rows: table.rows,
//       isLeaf: true
//     }))

//     resolve(tableNodes)
//   } catch (error) {
//     console.error('加载表列表失败:', error)
//     ElMessage.error('加载表列表失败')
//     resolve([])
//   }
// }

// 树节点点击事件
const handleNodeClick = async (data, node) => {
  console.log('点击节点:', data.type, data)

  if (data.type === 'instance') {
    // 点击实例节点，仅用于展开/折叠
    console.log('点击实例节点，展开/折叠')
  } else if (data.type === 'database') {
    // 点击数据库节点，仅用于展开/折叠，不自动连接
    console.log('点击数据库节点，展开/折叠')

    // 检查是否已连接到此数据库
    if (connectedDatabase.value === data.database) {
      console.log('已连接到此数据库，允许展开/折叠')
    } else {
      console.log('未连接到此数据库，请右键选择"连接到此数据库"')
      ElMessage.info(`请右键点击数据库"${data.database}"并选择"连接到此数据库"以查看表列表`)
    }
  } else if (data.type === 'table') {
    // 点击表节点，选择表并加载字段信息
    selectedTable.value = data.table
    currentDatabaseContext.value = data.database

    console.log('点击表节点:', data.table, '数据库:', data.database)

    // 使用带数据库上下文的字段加载
    await loadTableColumnsWithContext(data.database, data.table)

    // 移除弹出消息，静默选择表
    console.log(`已选择表: ${data.table}`)
  }
}

// 树节点右键菜单
const handleNodeRightClick = (event, data, node) => {
  event.preventDefault()
  console.log('右键点击节点:', data)

  // 设置右键菜单数据和位置
  contextMenuData.value = data
  contextMenuPosition.value = {
    x: event.clientX,
    y: event.clientY
  }
  contextMenuVisible.value = true

  // 点击其他地方关闭菜单
  const closeMenu = () => {
    contextMenuVisible.value = false
    document.removeEventListener('click', closeMenu)
  }

  setTimeout(() => {
    document.addEventListener('click', closeMenu)
  }, 100)
}

// 右键菜单操作
const contextMenuActions = {
  // 数据库级别操作
  connectToDatabase: async (data) => {
    if (data.type === 'database') {
      console.log('开始连接到数据库:', data.database, '节点ID:', data.id)

      currentDatabaseContext.value = data.database
      connectedDatabase.value = data.database

      // 确保selectedDatabase被设置，以启用执行查询按钮
      if (!selectedDatabase.value) {
        selectedDatabase.value = data.instanceId
        console.log('设置selectedDatabase为:', data.instanceId)
      } else {
        console.log('selectedDatabase已存在:', selectedDatabase.value)
      }

      console.log('连接数据库后的状态:', {
        selectedDatabase: selectedDatabase.value,
        connectedDatabase: connectedDatabase.value,
        currentDatabaseContext: currentDatabaseContext.value
      })

      // 清空之前的表选择和查询结果
      selectedTable.value = null
      tableColumns.value = []

      // 清空所有标签页的结果
      queryTabs.value.forEach(tab => {
        tab.result = null
        tab.error = null
      })

      // 关闭右键菜单
      contextMenuVisible.value = false

      try {
        // 获取树节点
        const node = treeRef.value?.getNode(data.id)
        console.log('找到的树节点:', node)

        if (node) {
          // 确保节点在展开的键列表中
          if (!expandedKeys.value.includes(data.id)) {
            expandedKeys.value.push(data.id)
          }

          // 展开节点（这会触发懒加载）
          node.expand()
          console.log('节点已展开，懒加载将自动触发')

        } else {
          console.error('未找到对应的树节点:', data.id)
        }

        ElMessage.success(`已连接到数据库: ${data.database}，点击数据库节点查看表列表`)

        console.log('连接完成:', {
          database: data.database,
          instanceId: data.instanceId,
          currentDatabaseContext: currentDatabaseContext.value,
          connectedDatabase: connectedDatabase.value,
          expandedKeys: expandedKeys.value
        })

      } catch (error) {
        console.error('连接数据库时出错:', error)
        ElMessage.error(`连接到数据库 ${data.database} 时出错: ${error.message}`)
      }
    }
  },

  refreshDatabase: async (data) => {
    if (data.type === 'database') {
      ElMessage.info(`刷新数据库 ${data.database} 中...`)
      // 重新加载该数据库的表列表
      const node = treeRef.value?.getNode(data.id)
      if (node) {
        node.loaded = false
        node.expand()
      }
      contextMenuVisible.value = false
    }
  },

  showDatabaseInfo: (data) => {
    if (data.type === 'database') {
      ElMessage.info(`数据库信息: ${data.database}`)
      // TODO: 显示数据库详细信息对话框
      contextMenuVisible.value = false
    }
  },

  // 表级别操作
  selectFromTable: (data) => {
    if (data.type === 'table') {
      const sql = `SELECT * FROM \`${data.table}\` LIMIT 100;`

      // 获取当前活动标签页
      const currentTab = getCurrentTab()

      // 如果当前标签页已有内容，创建新标签页
      if (currentTab && currentTab.sqlContent.trim()) {
        // 创建新标签页
        newQuery()

        // 等待新标签页创建完成后设置内容
        nextTick(() => {
          const newTab = getCurrentTab()
          if (newTab) {
            newTab.sqlContent = sql

            // 更新Monaco编辑器内容
            const editorRef = monacoEditorRefs.value[activeTabName.value]
            if (editorRef && editorRef.setValue) {
              editorRef.setValue(sql)
            }
          }
        })

        ElMessage.success(`已在新标签页生成 ${data.table} 表的查询语句`)
      } else if (currentTab) {
        // 当前标签页为空，直接设置内容
        currentTab.sqlContent = sql

        // 更新Monaco编辑器内容
        nextTick(() => {
          const editorRef = monacoEditorRefs.value[activeTabName.value]
          if (editorRef && editorRef.setValue) {
            editorRef.setValue(sql)
          }
        })

        ElMessage.success(`已生成 ${data.table} 表的查询语句`)
      }

      currentDatabaseContext.value = data.database
      contextMenuVisible.value = false
    }
  },

  showTableStructure: async (data) => {
    if (data.type === 'table') {
      selectedTable.value = data.table
      currentDatabaseContext.value = data.database
      await loadTableColumnsWithContext(data.database, data.table)
      ElMessage.success(`已加载表结构: ${data.table}`)
      contextMenuVisible.value = false
    }
  },

  insertIntoTable: (data) => {
    if (data.type === 'table') {
      const sql = `INSERT INTO \`${data.table}\` (column1, column2) VALUES (value1, value2);`

      // 获取当前活动标签页
      const currentTab = getCurrentTab()

      // 如果当前标签页已有内容，创建新标签页
      if (currentTab && currentTab.sqlContent.trim()) {
        // 创建新标签页
        newQuery()

        // 等待新标签页创建完成后设置内容
        nextTick(() => {
          const newTab = getCurrentTab()
          if (newTab) {
            newTab.sqlContent = sql

            // 更新Monaco编辑器内容
            const editorRef = monacoEditorRefs.value[activeTabName.value]
            if (editorRef && editorRef.setValue) {
              editorRef.setValue(sql)
            }
          }
        })

        ElMessage.success(`已在新标签页生成 ${data.table} 表的INSERT语句模板`)
      } else if (currentTab) {
        // 当前标签页为空，直接设置内容
        currentTab.sqlContent = sql

        // 更新Monaco编辑器内容
        nextTick(() => {
          const editorRef = monacoEditorRefs.value[activeTabName.value]
          if (editorRef && editorRef.setValue) {
            editorRef.setValue(sql)
          }
        })

        ElMessage.success(`已生成 ${data.table} 表的INSERT语句模板`)
      }

      currentDatabaseContext.value = data.database
      contextMenuVisible.value = false
    }
  },

  updateTable: (data) => {
    if (data.type === 'table') {
      const sql = `UPDATE \`${data.table}\` SET column1 = value1 WHERE condition;`

      // 获取当前活动标签页
      const currentTab = getCurrentTab()

      // 如果当前标签页已有内容，创建新标签页
      if (currentTab && currentTab.sqlContent.trim()) {
        // 创建新标签页
        newQuery()

        // 等待新标签页创建完成后设置内容
        nextTick(() => {
          const newTab = getCurrentTab()
          if (newTab) {
            newTab.sqlContent = sql

            // 更新Monaco编辑器内容
            const editorRef = monacoEditorRefs.value[activeTabName.value]
            if (editorRef && editorRef.setValue) {
              editorRef.setValue(sql)
            }
          }
        })

        ElMessage.success(`已在新标签页生成 ${data.table} 表的UPDATE语句模板`)
      } else if (currentTab) {
        // 当前标签页为空，直接设置内容
        currentTab.sqlContent = sql

        // 更新Monaco编辑器内容
        nextTick(() => {
          const editorRef = monacoEditorRefs.value[activeTabName.value]
          if (editorRef && editorRef.setValue) {
            editorRef.setValue(sql)
          }
        })

        ElMessage.success(`已生成 ${data.table} 表的UPDATE语句模板`)
      }

      currentDatabaseContext.value = data.database
      contextMenuVisible.value = false
    }
  }
}

// 带数据库上下文的表字段加载
const loadTableColumnsWithContext = async (database, tableName) => {
  if (!selectedDatabase.value || !tableName) return

  try {
    const currentDb = getCurrentDatabase()
    let sql = ''

    if (currentDb?.database_type === 'mysql') {
      sql = `DESCRIBE \`${database}\`.\`${tableName}\``
    } else if (currentDb?.database_type === 'postgresql') {
      sql = `SELECT column_name, data_type, is_nullable, column_default FROM information_schema.columns WHERE table_name = '${tableName}'`
    } else if (currentDb?.database_type === 'sqlite') {
      sql = `PRAGMA table_info(${tableName})`
    } else {
      sql = `DESCRIBE \`${database}\`.\`${tableName}\``
    }

    const response = await sqlAPI.executeQuery({
      database_id: selectedDatabase.value,
      sql_content: sql,
      limit: 1000
    })

    if (response && response.result && response.result.rows) {
      // 根据数据库类型处理字段信息
      if (currentDb?.database_type === 'mysql') {
        tableColumns.value = response.result.rows.map(row => ({
          name: row[0],
          type: row[1],
          null: row[2],
          key: row[3],
          default: row[4] || null,
          extra: row[5] || ''
        }))
      } else if (currentDb?.database_type === 'postgresql') {
        tableColumns.value = response.result.rows.map(row => ({
          name: row[0],
          type: row[1],
          null: row[2],
          key: '',
          default: row[3] || null,
          extra: ''
        }))
      } else {
        tableColumns.value = response.result.rows.map(row => ({
          name: row[1] || row[0],
          type: row[2] || row[1],
          null: row[3] || 'YES',
          key: '',
          default: row[4] || null,
          extra: ''
        }))
      }
    } else {
      tableColumns.value = []
    }
  } catch (error) {
    console.error('加载表字段失败:', error)
    tableColumns.value = []
  }
}

// 树节点过滤
const filterNode = (value, data) => {
  if (!value) return true
  return data.label.toLowerCase().includes(value.toLowerCase())
}

// 加载表字段信息（从API）
const loadTableColumnsFromAPI = async (database, table) => {
  try {
    const response = await sqlAPI.getTableStructure(selectedDatabase.value, database, table)
    tableColumns.value = response.data || response || []
  } catch (error) {
    console.error('加载表字段失败:', error)
    ElMessage.error('加载表字段失败')
    tableColumns.value = []
  }
}

// 监听搜索文本变化
watch(searchText, (val) => {
  if (treeRef.value) {
    treeRef.value.filter(val)
  }
})

// 监听数据库选择变化（仅用于程序化设置时的处理）
watch(selectedDatabase, async (newVal, oldVal) => {
  // 只有在程序化设置时才处理（避免与handleDatabaseChange重复）
  if (newVal && newVal !== oldVal) {
    console.log('Watch监听到数据库变化:', newVal, '旧值:', oldVal)

    // 检查是否是通过handleDatabaseChange设置的，如果是则跳过
    // 这里可以通过检查当前状态来判断
    const currentDb = getCurrentDatabase()
    if (currentDb && !currentDb.database_name && treeData.value.length === 0) {
      console.log('Watch触发数据库列表加载')
      await loadDatabaseList()
    }
  }
})

// 显示新建连接对话框
const showAddConnectionDialog = () => {
  // 重置表单数据
  connectionForm.value = {
    name: '',
    database_type: 'mysql',
    host: 'localhost',
    port: 3306,
    database_name: '',
    username: '',
    password: '',
    description: ''
  }

  editMode.value = false // 设置为新建模式
  addConnectionDialogVisible.value = true

  // 确保端口值正确显示
  nextTick(() => {
    handleDatabaseTypeChange('mysql')
  })
}

// 对话框关闭后的回调
const onDialogClosed = () => {
  editMode.value = false
  // 重置表单数据
  connectionForm.value = {
    name: '',
    database_type: 'mysql',
    host: 'localhost',
    port: 3306,
    database_name: '',
    username: '',
    password: '',
    description: ''
  }
}

// 对话框打开后的回调
const onDialogOpened = () => {
  nextTick(() => {
    // 清除表单验证状态
    if (connectionFormRef.value) {
      connectionFormRef.value.clearValidate()
    }

    // 确保端口字段显示正确的默认值
    const currentType = connectionForm.value.database_type
    if (currentType) {
      handleDatabaseTypeChange(currentType)
    }
  })
}

// 测试连接
const testConnectionBeforeSave = async () => {
  try {
    await connectionFormRef.value.validate()
    testingConnection.value = true

    console.log('开始测试连接，参数:', connectionForm.value)

    // 直接调用测试连接API，传递连接参数
    const response = await sqlAPI.testConnectionWithParams(connectionForm.value)

    console.log('API响应:', response)

    // 由于axios拦截器返回response.data，所以直接访问response的属性
    if (response && response.success) {
      ElMessage.success(`连接测试成功！连接时间: ${response.connection_time}s`)
      if (response.version) {
        ElMessage.info(`数据库版本: ${response.version}`)
      }
    } else {
      const errorMessage = response?.message || '连接测试失败'
      ElMessage.error(`连接测试失败: ${errorMessage}`)
    }
  } catch (error) {
    console.error('连接测试失败:', error)

    // 改进错误处理
    let errorMessage = '连接测试失败'
    if (error.response?.data?.error) {
      errorMessage = error.response.data.error
    } else if (error.response?.data?.message) {
      errorMessage = error.response.data.message
    } else if (error.message) {
      errorMessage = error.message
    }

    ElMessage.error(errorMessage)
  } finally {
    testingConnection.value = false
  }
}

// 保存连接
const saveConnection = async () => {
  try {
    await connectionFormRef.value.validate()
    savingConnection.value = true

    if (editMode.value) {
      // 编辑模式：更新连接
      const connectionId = connectionForm.value.id
      const updateData = { ...connectionForm.value }
      delete updateData.id // 移除id字段，避免传递给后端

      await sqlAPI.updateDatabaseInstance(connectionId, updateData)
      ElMessage.success('数据库连接更新成功')

      // 如果修改的是当前连接且改了数据库名，重新加载表结构
      if (selectedDatabase.value === connectionId) {
        await loadTableStructure()
      }
    } else {
      // 新建模式：创建连接
      const response = await sqlAPI.createDatabaseInstance(connectionForm.value)
      ElMessage.success('数据库连接创建成功')

      // 自动选择新创建的数据库实例
      const newConnectionId = response.data?.id || response.id
      if (newConnectionId) {
        console.log('自动选择新创建的数据库实例:', newConnectionId)
        selectedDatabase.value = newConnectionId

        // 触发数据库变化处理
        await handleDatabaseChange(newConnectionId)
      }
    }

    addConnectionDialogVisible.value = false
    await loadDatabases()
  } catch (error) {
    console.error('保存连接失败:', error)
    const action = editMode.value ? '更新' : '创建'
    ElMessage.error(`${action}连接失败: ` + (error.response?.data?.error || error.message))
  } finally {
    savingConnection.value = false
  }
}

// 执行SQL查询
const executeQuery = async () => {
  const currentTab = getCurrentTab()
  if (!selectedDatabase.value || !currentTab || !currentTab.sqlContent.trim()) {
    ElMessage.warning('请选择数据库实例并输入SQL语句')
    return
  }

  // 检查选择的数据库实例是否有数据库名称或已通过右键菜单连接到特定数据库
  const currentDb = getCurrentDatabase()
  if (currentDb && currentDb.database_type === 'mysql' && !currentDb.database_name && !currentDatabaseContext.value) {
    ElMessage.warning('所选数据库实例未指定数据库名称，请在左侧数据库浏览器中右键选择"连接到此数据库"，或重新配置该实例')
    return
  }

  executing.value = true
  currentTab.error = null

  try {
    // 获取要执行的SQL内容（支持选择性执行）
    let sqlToExecute = getSelectedSqlOrAll(currentTab.sqlContent)

    // 如果用户通过右键菜单连接到了特定数据库，且当前连接没有指定数据库名称，则添加USE语句
    if (currentDatabaseContext.value && currentDb && !currentDb.database_name) {
      const hasUserUseStatement = sqlToExecute.trim().toUpperCase().includes('USE ')
      if (!hasUserUseStatement) {
        if (currentDb.database_type === 'mysql') {
          sqlToExecute = `USE \`${currentDatabaseContext.value}\`;\n${sqlToExecute}`
        }
        console.log('添加数据库上下文，最终SQL:', sqlToExecute)
      }
    }

    console.log('执行查询，参数:', {
      database_id: selectedDatabase.value,
      sql_content: sqlToExecute,
      limit: 1000,
      currentDatabaseContext: currentDatabaseContext.value
    })

    // 清空当前标签页的结果
    currentTab.result = null
    currentTab.multiResults = []

    // 直接发送所有SQL到后端处理
    const response = await sqlAPI.executeQuery({
      database_id: selectedDatabase.value,
      sql_content: sqlToExecute,
      limit: 1000
    })

    console.log('查询响应:', response)

    // 处理查询结果
    if (response && response.result) {
      // 检查是否是多结果集响应
      if (response.result.multiple_results && response.result.results) {
        // 后端返回的是多结果集，过滤掉USE语句结果
        const filteredResults = response.result.results.filter(subResult => {
          const sqlType = subResult.sql_type || 'UNKNOWN'
          return sqlType !== 'USE'  // 不显示USE语句的结果
        })

        currentTab.multiResults = filteredResults.map((subResult, index) => ({
          id: `result-${Date.now()}-${index}`,
          sql: subResult.sql_content || '',
          sqlType: subResult.sql_type || 'UNKNOWN',
          tableName: extractTableName(subResult.sql_content || ''),
          columns: subResult.columns || [],
          rows: subResult.rows || [],
          execution_time: subResult.execution_time || 0,
          rows_affected: subResult.affected_rows || subResult.row_count || 0,
          message: subResult.message || `执行成功`,
          error: subResult.success === false ? subResult.error : null
        }))

        // 如果只有一个结果，也设置为主结果
        if (currentTab.multiResults.length === 1 && !currentTab.multiResults[0].error) {
          currentTab.result = currentTab.multiResults[0]
          currentTab.multiResults = null
        }

        // 显示执行完成消息（基于过滤后的结果）
        const successCount = filteredResults.filter(r => r.success !== false).length
        const errorCount = filteredResults.filter(r => r.success === false).length
        if (successCount > 0 || errorCount > 0) {
          ElMessage.success(`执行完成：${successCount}条成功，${errorCount}条失败`)
        }
      } else {
        // 单个结果
        console.log('处理单个查询结果:', {
          columns: response.result.columns,
          rowsLength: response.result.rows?.length,
          firstRow: response.result.rows?.[0]
        })

        currentTab.result = {
          id: `result-${Date.now()}`,
          sql: sqlToExecute,
          sqlType: response.result.sql_type || 'UNKNOWN',
          tableName: extractTableName(sqlToExecute),
          columns: response.result.columns,
          rows: response.result.rows,
          execution_time: response.result.execution_time || 0,
          rows_affected: response.result.rows_affected || response.result.rows?.length || 0,
          message: response.message || '查询执行成功'
        }

        console.log('设置tab.result:', currentTab.result)

        const message = response.message || '查询执行成功'
        ElMessage.success(message)
      }
    } else {
      console.error('响应格式错误:', response)
      throw new Error('响应数据格式错误')
    }

  } catch (error) {
    console.error('查询执行失败:', error)

    // 改进错误处理
    let errorMessage = '查询执行失败'
    if (error.response?.data?.error) {
      errorMessage = error.response.data.error
    } else if (error.error) {
      errorMessage = error.error
    } else if (error.message) {
      errorMessage = error.message
    }

    currentTab.error = errorMessage
    ElMessage.error(errorMessage)
  } finally {
    executing.value = false
  }
}

// SQL语句解析器
const parseSqlStatements = (sqlContent) => {
  if (!sqlContent || !sqlContent.trim()) {
    return []
  }

  const statements = []
  let currentStatement = ''
  let inString = false
  let stringChar = ''
  let inComment = false
  let commentType = ''

  for (let i = 0; i < sqlContent.length; i++) {
    const char = sqlContent[i]
    const nextChar = sqlContent[i + 1]

    // 处理注释
    if (!inString && !inComment) {
      if (char === '-' && nextChar === '-') {
        inComment = true
        commentType = 'line'
        currentStatement += char
        continue
      } else if (char === '/' && nextChar === '*') {
        inComment = true
        commentType = 'block'
        currentStatement += char
        continue
      }
    }

    // 处理注释结束
    if (inComment) {
      currentStatement += char
      if (commentType === 'line' && char === '\n') {
        inComment = false
        commentType = ''
      } else if (commentType === 'block' && char === '*' && nextChar === '/') {
        currentStatement += nextChar
        i++ // 跳过下一个字符
        inComment = false
        commentType = ''
      }
      continue
    }

    // 处理字符串
    if (!inComment) {
      if (!inString && (char === '"' || char === "'" || char === '`')) {
        inString = true
        stringChar = char
      } else if (inString && char === stringChar) {
        // 检查是否是转义字符
        if (sqlContent[i - 1] !== '\\') {
          inString = false
          stringChar = ''
        }
      }
    }

    currentStatement += char

    // 检查语句分隔符
    if (!inString && !inComment && char === ';') {
      const trimmedStatement = currentStatement.trim()
      if (trimmedStatement && trimmedStatement !== ';') {
        statements.push(trimmedStatement)
      }
      currentStatement = ''
    }
  }

  // 添加最后一个语句（如果没有以分号结尾）
  const trimmedStatement = currentStatement.trim()
  if (trimmedStatement) {
    statements.push(trimmedStatement)
  }

  return statements.filter(stmt => stmt && stmt.trim() !== '')
}

// 获取选中的SQL或全部SQL
const getSelectedSqlOrAll = (sqlContent) => {
  // 尝试获取当前活动标签页的textarea元素
  const currentTab = getCurrentTab()
  if (!currentTab) return sqlContent

  const textareaId = `sql-textarea-${currentTab.name}`
  const textarea = document.getElementById(textareaId)

  if (textarea && textarea.selectionStart !== textarea.selectionEnd) {
    // 有选中文本，返回选中的内容
    const selectedText = textarea.value.substring(textarea.selectionStart, textarea.selectionEnd).trim()
    console.log('检测到选中文本:', selectedText)
    return selectedText
  }

  // 没有选中文本，返回全部内容
  console.log('没有选中文本，使用全部内容')
  return sqlContent
}

// 识别SQL语句类型
const identifySqlType = (sql) => {
  const trimmedSql = sql.trim().toUpperCase()

  if (trimmedSql.startsWith('SELECT')) {
    return 'SELECT'
  } else if (trimmedSql.startsWith('INSERT')) {
    return 'INSERT'
  } else if (trimmedSql.startsWith('UPDATE')) {
    return 'UPDATE'
  } else if (trimmedSql.startsWith('DELETE')) {
    return 'DELETE'
  } else if (trimmedSql.startsWith('CREATE')) {
    return 'CREATE'
  } else if (trimmedSql.startsWith('DROP')) {
    return 'DROP'
  } else if (trimmedSql.startsWith('ALTER')) {
    return 'ALTER'
  } else if (trimmedSql.startsWith('SHOW')) {
    return 'SHOW'
  } else if (trimmedSql.startsWith('DESCRIBE') || trimmedSql.startsWith('DESC')) {
    return 'DESCRIBE'
  } else if (trimmedSql.startsWith('USE')) {
    return 'USE'
  } else {
    return 'OTHER'
  }
}

// 从SQL语句中提取表名（简单实现）
const extractTableName = (sql) => {
  const trimmedSql = sql.trim().toUpperCase()
  let tableName = ''

  if (trimmedSql.startsWith('SELECT')) {
    const fromMatch = sql.match(/FROM\s+`?([a-zA-Z_][a-zA-Z0-9_]*)`?/i)
    if (fromMatch) {
      tableName = fromMatch[1]
    }
  } else if (trimmedSql.startsWith('INSERT')) {
    const intoMatch = sql.match(/INSERT\s+INTO\s+`?([a-zA-Z_][a-zA-Z0-9_]*)`?/i)
    if (intoMatch) {
      tableName = intoMatch[1]
    }
  } else if (trimmedSql.startsWith('UPDATE')) {
    const updateMatch = sql.match(/UPDATE\s+`?([a-zA-Z_][a-zA-Z0-9_]*)`?/i)
    if (updateMatch) {
      tableName = updateMatch[1]
    }
  } else if (trimmedSql.startsWith('DELETE')) {
    const fromMatch = sql.match(/DELETE\s+FROM\s+`?([a-zA-Z_][a-zA-Z0-9_]*)`?/i)
    if (fromMatch) {
      tableName = fromMatch[1]
    }
  }

  return tableName
}

// 获取SQL类型对应的标签颜色
const getSqlTypeTag = (sqlType) => {
  switch (sqlType) {
    case 'SELECT':
      return 'primary'
    case 'INSERT':
      return 'success'
    case 'UPDATE':
      return 'warning'
    case 'DELETE':
      return 'danger'
    case 'CREATE':
      return 'info'
    case 'DROP':
      return 'danger'
    case 'ALTER':
      return 'warning'
    case 'SHOW':
    case 'DESCRIBE':
      return 'info'
    default:
      return ''
  }
}

// 获取结果标签页的标签名称
const getResultTabLabel = (result, index) => {
  if (result.error) {
    return `❌ 错误`
  }

  // 优先显示表名
  if (result.tableName) {
    if (result.sqlType === 'SELECT') {
      const rowCount = result.rows?.length || 0
      return `${result.tableName} (${rowCount}行)`
    } else {
      return `${result.sqlType} ${result.tableName}`
    }
  }

  // 如果没有表名，尝试从SQL中重新提取
  if (result.sql) {
    const extractedTableName = extractTableName(result.sql)
    if (extractedTableName) {
      if (result.sqlType === 'SELECT') {
        const rowCount = result.rows?.length || 0
        return `${extractedTableName} (${rowCount}行)`
      } else {
        return `${result.sqlType} ${extractedTableName}`
      }
    }
  }

  // 最后的备选方案
  if (result.sqlType === 'SELECT') {
    const rowCount = result.rows?.length || 0
    return `查询结果 (${rowCount}行)`
  }

  return result.sqlType || '查询结果'
}

// Monaco Editor已经内置了Ctrl+Enter执行功能和智能提示
// 这些功能已经在MonacoSQLEditor组件中处理

// Monaco Editor已经提供了完整的SQL智能提示功能
// 包括关键字、函数、表名等的自动补全

// 导出查询结果
const exportResults = (result) => {
  if (!result || !result.rows || result.rows.length === 0) {
    ElMessage.warning('没有可导出的数据')
    return
  }

  // 简单的CSV导出
  const csvContent = [
    result.columns.join(','),
    ...result.rows.map(row => row.join(','))
  ].join('\n')

  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  const url = URL.createObjectURL(blob)
  link.setAttribute('href', url)
  link.setAttribute('download', `query_result_${new Date().getTime()}.csv`)
  link.style.visibility = 'hidden'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)

  ElMessage.success('查询结果已导出为CSV文件')
}

// 新建查询
const newQuery = () => {
  tabCounter.value++
  const newTabName = `tab-${tabCounter.value}`
  const newTab = {
    name: newTabName,
    title: `查询${tabCounter.value}`,
    sqlContent: '',
    result: null,
    error: null,
    closable: true
  }

  queryTabs.value.push(newTab)
  activeTabName.value = newTabName

  ElMessage.success(`已创建新查询标签页: 查询${tabCounter.value}`)
}

// 切换左侧面板显示/隐藏
const toggleLeftPanel = () => {
  leftPanelCollapsed.value = !leftPanelCollapsed.value

  // 保存用户偏好到localStorage
  localStorage.setItem('sql-left-panel-collapsed', leftPanelCollapsed.value.toString())

  ElMessage.success(leftPanelCollapsed.value ? '已收起数据库结构面板' : '已展开数据库结构面板')
}

// 从localStorage恢复左侧面板状态
const restoreLeftPanelState = () => {
  const saved = localStorage.getItem('sql-left-panel-collapsed')
  if (saved !== null) {
    leftPanelCollapsed.value = saved === 'true'
  }
}



// 移除标签页
const removeTab = (targetName) => {
  const tabs = queryTabs.value
  let activeName = activeTabName.value

  if (activeName === targetName) {
    tabs.forEach((tab, index) => {
      if (tab.name === targetName) {
        const nextTab = tabs[index + 1] || tabs[index - 1]
        if (nextTab) {
          activeName = nextTab.name
        }
      }
    })
  }

  activeTabName.value = activeName
  queryTabs.value = tabs.filter(tab => tab.name !== targetName)

  ElMessage.success('已关闭查询标签页')
}

// 标签页点击事件
const handleTabClick = (tab) => {
  activeTabName.value = tab.props.name
}

// 获取当前活动标签页
const getCurrentTab = () => {
  return queryTabs.value.find(tab => tab.name === activeTabName.value)
}

// 获取数据库显示文本
const getDatabaseDisplayText = (db) => {
  if (connectedDatabase.value && db.id === selectedDatabase.value) {
    return `${db.name} - 已连接${connectedDatabase.value}`
  } else if (db.database_name) {
    return `${db.name} - ${db.database_name}`
  } else {
    return `${db.name} - 未指定数据库`
  }
}



// 加载表结构
const loadTableStructure = async () => {
  if (!selectedDatabase.value) return

  loadingTables.value = true
  try {
    // 根据数据库类型执行不同的查询
    const currentDb = getCurrentDatabase()

    console.log('当前数据库信息:', currentDb)
    console.log('选择的数据库ID:', selectedDatabase.value)

    if (!currentDb) {
      console.error('未找到当前数据库信息')
      ElMessage.error('未找到数据库连接信息')
      return
    }

    // 如果没有指定数据库名称且没有连接到特定数据库，显示数据库列表
    if (!currentDb.database_name && !currentDatabaseContext.value) {
      console.log('未指定数据库名称且未连接到特定数据库，加载数据库列表')
      await loadDatabaseList()
      return
    }

    let sql = ''

    // 如果有数据库上下文，先切换到该数据库
    if (currentDatabaseContext.value) {
      if (currentDb?.database_type === 'mysql') {
        sql = `USE \`${currentDatabaseContext.value}\`; SHOW TABLES`
      } else if (currentDb?.database_type === 'postgresql') {
        sql = "SELECT tablename as table_name FROM pg_tables WHERE schemaname = 'public'"
      } else if (currentDb?.database_type === 'sqlite') {
        sql = "SELECT name as table_name FROM sqlite_master WHERE type='table'"
      } else {
        sql = `USE \`${currentDatabaseContext.value}\`; SHOW TABLES`
      }
    } else if (currentDb.database_name) {
      // 如果实例指定了数据库名称，使用实例的数据库
      if (currentDb?.database_type === 'mysql') {
        sql = `USE \`${currentDb.database_name}\`; SHOW TABLES`
      } else if (currentDb?.database_type === 'postgresql') {
        sql = "SELECT tablename as table_name FROM pg_tables WHERE schemaname = 'public'"
      } else if (currentDb?.database_type === 'sqlite') {
        sql = "SELECT name as table_name FROM sqlite_master WHERE type='table'"
      } else {
        sql = `USE \`${currentDb.database_name}\`; SHOW TABLES`
      }
    } else {
      // 没有指定数据库，只执行SHOW TABLES（可能会失败）
      if (currentDb?.database_type === 'mysql') {
        sql = 'SHOW TABLES'
      } else if (currentDb?.database_type === 'postgresql') {
        sql = "SELECT tablename as table_name FROM pg_tables WHERE schemaname = 'public'"
      } else if (currentDb?.database_type === 'sqlite') {
        sql = "SELECT name as table_name FROM sqlite_master WHERE type='table'"
      } else {
        sql = 'SHOW TABLES'
      }
    }

    console.log('执行SQL:', sql)
    console.log('请求参数:', {
      database_id: selectedDatabase.value,
      sql_content: sql,
      limit: 1000
    })

    const response = await sqlAPI.executeQuery({
      database_id: selectedDatabase.value,
      sql_content: sql,
      limit: 1000
    })

    // 处理响应数据
    let tableRows = []

    if (response && response.result) {
      if (response.result.multiple_results && response.result.results) {
        // 多语句执行结果，找到SHOW TABLES的结果
        const showTablesResult = response.result.results.find(r =>
          r.sql_type === 'SHOW' && r.rows && r.rows.length > 0
        )
        if (showTablesResult) {
          tableRows = showTablesResult.rows
        }
      } else if (response.result.rows) {
        // 单语句执行结果
        tableRows = response.result.rows
      }
    }

    if (tableRows.length > 0) {
      tables.value = tableRows.map(row => ({
        name: row[0],
        rows: null // 可以后续添加行数统计
      }))
      console.log(`成功加载 ${tables.value.length} 个表:`, tables.value.map(t => t.name))
    } else {
      tables.value = []
      console.log('未找到表数据')
    }

    // 构建树形数据
    buildTreeData()
  } catch (error) {
    console.error('加载表结构失败:', error)
    console.error('错误详情:', {
      status: error.response?.status,
      statusText: error.response?.statusText,
      data: error.response?.data,
      config: error.config
    })

    let errorMessage = '加载表结构失败'
    if (error.response?.data?.error) {
      errorMessage += ': ' + error.response.data.error
    } else if (error.response?.data?.detail) {
      errorMessage += ': ' + error.response.data.detail
    } else if (error.message) {
      errorMessage += ': ' + error.message
    }

    ElMessage.error(errorMessage)
    tables.value = []
    treeData.value = []
  } finally {
    loadingTables.value = false
  }
}

// 加载数据库列表（当未指定数据库名称时）
const loadDatabaseList = async () => {
  const currentDb = getCurrentDatabase()
  if (!currentDb) {
    console.log('没有选择数据库实例，跳过加载数据库列表')
    return
  }

  try {
    loadingTree.value = true
    console.log('开始获取数据库列表，实例ID:', selectedDatabase.value, '实例信息:', currentDb)

    // 使用新的API获取数据库列表（不包含系统数据库）
    const response = await sqlAPI.getDatabaseList(selectedDatabase.value, false)
    console.log('数据库列表API响应:', response)

    if (response && response.databases && Array.isArray(response.databases)) {
      databaseList.value = response.databases
      console.log('成功获取数据库列表:', databaseList.value)
      console.log('数据库名称列表:', databaseList.value.map(db => db.name))

      // 构建三级树形结构
      buildDatabaseBrowserTree()

      ElMessage.success(`成功加载 ${databaseList.value.length} 个数据库`)
    } else {
      console.log('API响应中没有数据库列表或格式不正确')
      databaseList.value = []
      treeData.value = []

      // 显示空状态
      const instanceNode = {
        id: `instance_${currentDb.id}`,
        label: `${currentDb.name} (${currentDb.database_type}) - 无可访问数据库`,
        type: 'instance',
        instanceId: currentDb.id,
        isLeaf: true,
        children: []
      }
      treeData.value = [instanceNode]
      expandedKeys.value = [instanceNode.id]

      ElMessage.warning('该数据库实例下没有可访问的数据库')
    }
  } catch (error) {
    console.error('获取数据库列表失败:', error)

    let errorMessage = '获取数据库列表失败'
    if (error.response?.data?.error) {
      errorMessage = error.response.data.error
    } else if (error.message) {
      errorMessage = error.message
    }

    ElMessage.error(errorMessage)
    databaseList.value = []
    treeData.value = []

    // 显示错误状态
    const instanceNode = {
      id: `instance_${currentDb.id}`,
      label: `${currentDb.name} (${currentDb.database_type}) - 加载失败`,
      type: 'instance',
      instanceId: currentDb.id,
      isLeaf: true,
      children: []
    }
    treeData.value = [instanceNode]
    expandedKeys.value = [instanceNode.id]
  } finally {
    loadingTree.value = false
  }
}

// 构建数据库浏览器树形结构（三级）
const buildDatabaseBrowserTree = () => {
  const currentDb = getCurrentDatabase()
  if (!currentDb) {
    console.log('没有当前数据库实例，无法构建树形结构')
    treeData.value = []
    return
  }

  console.log('构建数据库浏览器树形结构，数据库列表:', databaseList.value)

  // 确保treeData是响应式的
  nextTick(() => {
    console.log('nextTick中构建树形结构')
  })

  if (!databaseList.value || databaseList.value.length === 0) {
    console.log('数据库列表为空，创建空的实例节点')
    const instanceNode = {
      id: `instance_${currentDb.id}`,
      label: `${currentDb.name} (${currentDb.database_type}) - 无数据库`,
      type: 'instance',
      instanceId: currentDb.id,
      isLeaf: true,
      children: []
    }
    treeData.value = [instanceNode]
    expandedKeys.value = [instanceNode.id]
    return
  }

  // 创建数据库节点
  const databaseNodes = databaseList.value.map(db => {
    const dbName = typeof db === 'string' ? db : db.name
    return {
      id: `db_${currentDb.id}_${dbName}`,
      label: dbName,
      type: 'database',
      database: dbName,
      instanceId: currentDb.id,
      isLeaf: false,
      children: [] // 懒加载表列表
    }
  })

  console.log('创建的数据库节点:', databaseNodes)

  // 创建实例根节点
  const instanceNode = {
    id: `instance_${currentDb.id}`,
    label: `${currentDb.name} (${currentDb.database_type}) - ${databaseNodes.length}个数据库`,
    type: 'instance',
    instanceId: currentDb.id,
    isLeaf: false,
    children: databaseNodes
  }

  treeData.value = [instanceNode]

  // 默认展开实例节点
  expandedKeys.value = [instanceNode.id]

  console.log('构建完成的树形结构:', treeData.value)

  // 强制触发响应式更新
  nextTick(() => {
    console.log('树形结构更新完成，当前treeData长度:', treeData.value.length)
  })
}

// 构建树形数据
const buildTreeData = () => {
  const currentDb = getCurrentDatabase()
  if (!currentDb || !tables.value.length) {
    treeData.value = []
    return
  }

  // 创建表节点
  const tableNodes = tables.value.map(table => ({
    id: `table_${table.name}`,
    label: table.name,
    type: 'table',
    database: currentDb.database_name || 'default',
    table: table.name,
    rows: table.rows,
    isLeaf: true
  }))

  // 创建数据库节点
  const databaseNode = {
    id: `db_${currentDb.database_name || 'default'}`,
    label: currentDb.database_name || currentDb.name,
    type: 'database',
    database: currentDb.database_name || 'default',
    isLeaf: false,
    children: tableNodes
  }

  treeData.value = [databaseNode]

  // 默认展开数据库节点
  expandedKeys.value = [databaseNode.id]
}

// 选择表
const selectTable = (tableName) => {
  selectedTable.value = tableName
  loadTableColumns(tableName)
}

// 加载表字段信息
const loadTableColumns = async (tableName) => {
  if (!selectedDatabase.value || !tableName) return

  try {
    const currentDb = getCurrentDatabase()
    let sql = ''

    if (currentDb?.database_type === 'mysql') {
      sql = `DESCRIBE \`${tableName}\``
    } else if (currentDb?.database_type === 'postgresql') {
      sql = `SELECT column_name, data_type, is_nullable, column_default FROM information_schema.columns WHERE table_name = '${tableName}'`
    } else if (currentDb?.database_type === 'sqlite') {
      sql = `PRAGMA table_info(${tableName})`
    } else {
      sql = `DESCRIBE \`${tableName}\``
    }

    const response = await sqlAPI.executeQuery({
      database_id: selectedDatabase.value,
      sql_content: sql,
      limit: 1000
    })

    if (response && response.result && response.result.rows) {
      // 根据数据库类型处理字段信息
      if (currentDb?.database_type === 'mysql') {
        tableColumns.value = response.result.rows.map(row => ({
          name: row[0],
          type: row[1],
          null: row[2],
          key: row[3],
          default: row[4],
          extra: row[5]
        }))
      } else {
        // 其他数据库类型的处理可以后续添加
        tableColumns.value = response.result.rows.map((row, index) => ({
          name: row[0],
          type: row[1] || 'unknown',
          null: row[2] || 'YES',
          key: '',
          default: row[3] || null,
          extra: ''
        }))
      }
    } else {
      tableColumns.value = []
    }
  } catch (error) {
    console.error('加载表字段失败:', error)
    tableColumns.value = []
  }
}

// 插入表名到SQL编辑器
const insertTableName = (tableName) => {
  const currentTab = getCurrentTab()
  if (!currentTab) {
    ElMessage.warning('请先创建查询标签页')
    return
  }

  const currentContent = currentTab.sqlContent
  const cursorPos = currentContent.length

  // 简单的插入逻辑，可以后续改进为光标位置插入
  if (currentContent.trim()) {
    currentTab.sqlContent = currentContent + ' ' + tableName
  } else {
    currentTab.sqlContent = `SELECT * FROM \`${tableName}\` LIMIT 10`
  }

  ElMessage.success(`已插入表名: ${tableName}`)
}

// 插入字段名到SQL编辑器
const insertColumnName = (columnName) => {
  const currentTab = getCurrentTab()
  if (!currentTab) {
    ElMessage.warning('请先创建查询标签页')
    return
  }

  const currentContent = currentTab.sqlContent

  if (currentContent.trim()) {
    currentTab.sqlContent = currentContent + ' ' + columnName
  } else {
    currentTab.sqlContent = columnName
  }

  ElMessage.success(`已插入字段名: ${columnName}`)
}

// 工单相关方法
const loadUserInfo = async () => {
  try {
    // 1. 先尝试从localStorage获取缓存
    const cachedUserInfo = localStorage.getItem('user_info')
    if (cachedUserInfo) {
      try {
        const userData = JSON.parse(cachedUserInfo)
        console.log('localStorage中的用户信息:', userData)

        // 如果是admin用户但没有权限字段，手动添加
        if (userData.username === 'admin' && userData.is_superuser === undefined) {
          userData.is_superuser = true
          userData.is_staff = true
          userData.is_active = true
          localStorage.setItem('user_info', JSON.stringify(userData))
          console.log('为admin用户添加权限信息:', userData)
        }

        userInfo.value = userData
        console.log('从缓存加载用户信息成功:', userData)
        return
      } catch (e) {
        console.error('解析缓存用户信息失败:', e)
      }
    }

    // 2. 如果缓存没有信息，尝试从认证API获取
    console.log('从服务器获取用户信息...')
    try {
      const authResponse = await fetch('/api/auth/profile/', {
        headers: {
          'Authorization': 'Bearer ' + localStorage.getItem('access_token'),
          'Content-Type': 'application/json'
        }
      })

      if (authResponse.ok) {
        const userData = await authResponse.json()
        userInfo.value = userData
        localStorage.setItem('user_info', JSON.stringify(userData))
        console.log('从认证API加载用户信息成功:', userData)
        return
      } else {
        console.warn('认证API返回错误:', authResponse.status, await authResponse.text())
      }
    } catch (authError) {
      console.warn('认证API调用失败:', authError)
    }

    // 3. 尝试从用户管理API获取
    try {
      const response = await sqlAPI.getCurrentUserInfo()
      if (response && response.user) {
        userInfo.value = response.user
        localStorage.setItem('user_info', JSON.stringify(response.user))
        console.log('从用户管理API加载用户信息成功:', response.user)
        return
      }
    } catch (apiError) {
      console.warn('用户管理API调用失败:', apiError)
    }

    throw new Error('所有API都无法获取用户信息')

  } catch (error) {
    console.error('获取用户信息失败:', error)

    // 4. 最后设置默认值
    console.warn('未找到用户信息，使用默认值')
    userInfo.value = {
      username: 'unknown',
      is_superuser: false,
      is_staff: false
    }
  }
}

const loadAdminUsers = async () => {
  try {
    const response = await sqlWorkOrderAPI.getAdminUsers()

    // 处理新的响应格式
    if (response.reviewers) {
      adminUsers.value = response.reviewers
      reviewerInfo.value = {
        userInGroup: response.user_in_group,
        groupNames: response.group_names || [],
        totalCount: response.total_count || 0
      }
    } else {
      // 兼容旧格式
      adminUsers.value = response
      reviewerInfo.value = {
        userInGroup: false,
        groupNames: [],
        totalCount: response.length || 0
      }
    }

    // 初始化过滤列表
    filteredAdminUsers.value = adminUsers.value
  } catch (error) {
    console.error('加载管理员用户失败:', error)
    ElMessage.error('加载管理员用户失败')
  }
}

// 审核人过滤函数
const filterReviewers = (query) => {
  // 暂时简化，直接返回，让用户能看到所有选项
  console.log('过滤查询:', query)
}

// 格式化用户名用于选项显示
const formatUsernameForOption = (user) => {
  const displayName = formatUsername(user)
  const realName = user.first_name || user.username
  return `${displayName} (${realName})`
}

const submitWorkOrder = async () => {
  try {
    // 验证必填字段
    if (!workOrderForm.title.trim()) {
      ElMessage.error('请输入工单标题')
      return
    }

    if (!workOrderForm.description.trim()) {
      ElMessage.error('请输入申请原因')
      return
    }

    // 设置工单数据
    const currentTab = getCurrentTab()
    const currentDb = getCurrentDatabase()

    const workOrderData = {
      title: workOrderForm.title,
      description: workOrderForm.description,
      sql_content: currentTab.sqlContent,
      request_type: 'dml', // 根据SQL类型自动判断
      database_instance: currentDb.id,
      reviewer: workOrderForm.reviewer,
      priority: workOrderForm.priority,
      expected_execution_time: workOrderForm.expected_execution_time
    }

    await sqlWorkOrderAPI.createWorkOrder(workOrderData)

    ElMessage.success('工单提交成功，请等待审核')
    showWorkOrderDialog.value = false

    // 重置表单
    Object.assign(workOrderForm, {
      title: '',
      description: '',
      sql_content: '',
      request_type: 'dml',
      database_instance: null,
      reviewer: null,
      priority: 'normal',
      expected_execution_time: null
    })

  } catch (error) {
    console.error('提交工单失败:', error)
    ElMessage.error('提交工单失败: ' + (error.response?.data?.error || error.message))
  }
}

// 监听工单对话框打开，自动填充数据
watch(showWorkOrderDialog, (newVal) => {
  if (newVal) {
    const currentTab = getCurrentTab()
    const currentDb = getCurrentDatabase()

    if (currentTab && currentDb) {
      workOrderForm.sql_content = currentTab.sqlContent
      workOrderForm.database_instance = currentDb.id

      // 自动生成标题
      if (!workOrderForm.title) {
        const sql = currentTab.sqlContent.trim().toUpperCase()
        if (sql.startsWith('INSERT')) {
          workOrderForm.title = '数据插入申请'
        } else if (sql.startsWith('UPDATE')) {
          workOrderForm.title = '数据更新申请'
        } else if (sql.startsWith('DELETE')) {
          workOrderForm.title = '数据删除申请'
        } else {
          workOrderForm.title = 'SQL执行申请'
        }
      }
    }

    // 加载管理员用户
    loadAdminUsers()
  }
})

// 水平拖动调整树形结构和字段列表的比例
const startHorizontalResize = (e) => {
  isResizing.value = true
  const startY = e.clientY
  const startHeight = treeContentHeight.value

  const handleMouseMove = (e) => {
    if (!isResizing.value) return

    const deltaY = e.clientY - startY
    const newHeight = Math.max(200, Math.min(800, startHeight + deltaY))
    treeContentHeight.value = newHeight

    // 保存到localStorage
    localStorage.setItem('treeContentHeight', newHeight.toString())
  }

  const handleMouseUp = () => {
    isResizing.value = false
    document.removeEventListener('mousemove', handleMouseMove)
    document.removeEventListener('mouseup', handleMouseUp)
    document.body.style.cursor = ''
    document.body.style.userSelect = ''
  }

  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('mouseup', handleMouseUp)
  document.body.style.cursor = 'ns-resize'
  document.body.style.userSelect = 'none'

  e.preventDefault()
}

// 恢复树形结构高度
const restoreTreeContentHeight = () => {
  const savedHeight = localStorage.getItem('treeContentHeight')
  if (savedHeight) {
    treeContentHeight.value = parseInt(savedHeight)
  }
}

// 动态控制树形结构高度
const updateTreeContentClass = () => {
  nextTick(() => {
    const treeContentEl = document.querySelector('.tree-content')
    if (treeContentEl) {
      if (selectedTable.value && tableColumns.value.length > 0) {
        treeContentEl.classList.remove('full-height')
      } else {
        treeContentEl.classList.add('full-height')
      }
    }
  })
}

// 监听字段数据变化
watch([selectedTable, tableColumns], () => {
  updateTreeContentClass()
}, { immediate: true })

// 页面加载
onMounted(async () => {
  loadDatabases()
  restoreLeftPanelState() // 恢复左侧面板状态
  restoreTreeContentHeight() // 恢复树形结构高度
  updateTreeContentClass() // 初始化树形结构高度类
  await loadUserInfo() // 加载用户信息
})
</script>

<style scoped>
.query-sql {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
}

/* 顶部工具栏 */
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: white;
  border-bottom: 1px solid #e4e7ed;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.database-select {
  display: flex;
  align-items: center;
  gap: 15px;
}

.current-database-context {
  margin-left: 12px;
}

.current-database-context .el-tag {
  display: flex;
  align-items: center;
  gap: 4px;
}

.toolbar-actions {
  display: flex;
  gap: 10px;
}

.database-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  min-height: 40px;
  padding: 4px 0;
}

/* 数据库树形结构样式 */
.database-tree-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  min-height: 0;
}

.tree-search {
  padding: 12px;
  border-bottom: 1px solid #ebeef5;
}

.tree-content {
  overflow: auto;
  padding: 8px;
  min-height: 0;
}

/* 当没有字段区域时，树形结构占满剩余空间 */
.database-tree-container:not(:has(.columns-section)) .tree-content {
  flex: 1;
}

/* 兼容性：对于不支持:has()的浏览器，使用JavaScript控制 */
.tree-content.full-height {
  flex: 1;
}

.tree-node {
  display: flex;
  align-items: center;
  gap: 6px;
  width: 100%;
}

.node-label {
  flex: 1;
  font-size: 14px;
  color: #303133;
}

.table-rows {
  font-size: 12px;
  color: #909399;
  margin-left: auto;
}

.el-tree {
  background: transparent;
}

.el-tree-node__content {
  height: 32px;
  border-radius: 4px;
  margin: 2px 0;
}

.el-tree-node__content:hover {
  background-color: #f5f7fa;
}

.el-tree-node.is-current > .el-tree-node__content {
  background-color: #e6f7ff;
  color: #1890ff;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #909399;
}

.empty-state .el-icon {
  font-size: 48px;
  margin-bottom: 16px;
  color: #c0c4cc;
}

.empty-tip {
  font-size: 12px;
  margin-top: 8px;
}

/* 右键菜单样式 */
.context-menu {
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 4px 0;
  min-width: 160px;
}

.menu-group {
  padding: 0;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  cursor: pointer;
  font-size: 14px;
  color: #303133;
  transition: background-color 0.3s;
}

.menu-item:hover {
  background-color: #f5f7fa;
}

.menu-item .el-icon {
  margin-right: 8px;
  font-size: 16px;
  color: #606266;
}

.menu-divider {
  height: 1px;
  background-color: #e4e7ed;
  margin: 4px 0;
}

.db-info {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-width: 0;
}

.db-name {
  font-weight: 500;
  color: #303133;
}

.db-detail {
  font-size: 12px;
  color: #909399;
}

.db-warning {
  color: #e6a23c;
  font-size: 12px;
}

.db-option-actions {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-left: 12px;
  flex-shrink: 0;
  min-width: 80px;
  overflow: visible;
}

.db-option-actions .delete-btn {
  padding: 6px 8px;
  min-height: 28px;
  min-width: 28px;
  opacity: 0.7;
  transition: opacity 0.2s;
  font-size: 16px;
  line-height: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  position: relative;
  overflow: visible;
}

.db-option-actions .delete-btn:hover {
  opacity: 1;
}

.db-option-actions .delete-btn .el-icon {
  font-size: 12px;
}

/* Element Plus 下拉选项样式覆盖 */
.el-select-dropdown .el-select-dropdown__item {
  height: auto !important;
  min-height: 48px !important;
  padding: 4px 20px !important;
  line-height: normal !important;
  overflow: visible !important;
}

.el-select-dropdown .el-select-dropdown__item .database-option {
  width: 100%;
  overflow: visible;
}

/* 确保下拉框容器不会截断内容 */
.el-select-dropdown {
  overflow: visible !important;
}

.el-select-dropdown__wrap {
  overflow: visible !important;
}

/* 针对我们的删除按钮的特殊样式 */
.el-select-dropdown .el-select-dropdown__item .db-option-actions .delete-btn {
  position: relative;
  z-index: 10;
  background: var(--el-color-danger);
  color: white;
  border: none;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

/* 主要内容区域 */
.main-content {
  flex: 1;
  display: flex;
  min-height: calc(100vh - 80px);
  min-width: 0;
}

/* 左侧面板 (1/3) */
.left-panel {
  width: 300px;
  min-width: 250px;
  max-width: 400px;
  background: white;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  transition: all 0.3s ease;
}

.panel-header {
  padding: 18px 20px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(135deg, #f8f9fa 0%, #f1f3f4 100%);
  box-shadow: 0 1px 3px rgba(0,0,0,0.05);
  min-height: 70px;
}



/* 面板标题容器 */
.panel-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.panel-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #1f2328;
  display: flex;
  align-items: center;
  gap: 8px;
}

.panel-header h3::before {
  content: '⚡';
  font-size: 18px;
  color: #0969da;
}

/* 折叠按钮样式 */
.collapse-btn {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border: 1px solid #dee2e6;
  color: #495057;
  width: 32px;
  height: 32px;
  padding: 0;
  border-radius: 6px;
  transition: all 0.2s ease;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.collapse-btn:hover {
  background: linear-gradient(135deg, #e9ecef 0%, #dee2e6 100%);
  border-color: #adb5bd;
  color: #0969da;
  transform: translateY(-1px);
  box-shadow: 0 2px 6px rgba(0,0,0,0.15);
}

.collapse-btn:active {
  transform: translateY(0);
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}



.current-database {
  margin-bottom: 20px;
  padding: 12px;
  background: #f0f9ff;
  border-radius: 6px;
  border-left: 3px solid #409eff;
}

.db-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 4px;
}

.db-main-info {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.db-main-info span {
  font-weight: 500;
  color: #303133;
}

.db-actions {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-left: 8px;
}

.db-actions .el-button {
  padding: 4px 8px;
  min-height: auto;
}

.db-actions .el-button .el-icon {
  font-size: 14px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  font-weight: 500;
  color: #303133;
}

.loading-state {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #909399;
  padding: 20px;
  text-align: center;
}

.tables-list {
  max-height: 300px;
  overflow-y: auto;
}

.table-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  margin-bottom: 4px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
}

.table-item:hover {
  background: #f0f9ff;
}

.table-item.active {
  background: #409eff;
  color: white;
}

.table-name {
  flex: 1;
  font-size: 14px;
}

.table-rows {
  font-size: 12px;
  color: #909399;
}

.table-item.active .table-rows {
  color: rgba(255, 255, 255, 0.8);
}

.columns-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.horizontal-resize-handle {
  height: 8px;
  cursor: ns-resize;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 2px 0;
  position: relative;
  user-select: none;
  background: transparent;
  transition: background-color 0.2s;
}

.horizontal-resize-handle:hover {
  background-color: rgba(64, 158, 255, 0.1);
}

.horizontal-resize-line {
  width: 60px;
  height: 2px;
  background-color: #dcdfe6;
  border-radius: 1px;
  transition: all 0.2s;
}

.horizontal-resize-handle:hover .horizontal-resize-line {
  background-color: #409eff;
  width: 80px;
  height: 3px;
}

.columns-list {
  flex: 1;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background: #fafafa;
  min-height: 0;
}

.column-item {
  padding: 8px 12px;
  margin-bottom: 4px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
  border-left: 2px solid transparent;
}

.column-item:hover {
  background: #f0f9ff;
  border-left-color: #409eff;
}

.column-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.column-name {
  font-weight: 500;
  color: #303133;
}

.column-type {
  font-size: 12px;
  color: #909399;
  background: #f0f2f5;
  padding: 2px 6px;
  border-radius: 3px;
}

.column-attrs {
  display: flex;
  gap: 4px;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #909399;
}

.no-database {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
}

.no-database .el-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

/* 右侧面板 (2/3) */
.right-panel {
  flex: 1;
  min-width: 0;
  background: white;
  display: flex;
  flex-direction: column;
}

/* 查询标签页 */
.query-tabs {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.query-tabs .el-tabs {
  display: flex;
  flex-direction: column;
}

.query-tabs .el-tabs__content {
  flex: 1;
}

.query-tabs .el-tab-pane {
  display: flex;
  flex-direction: column;
}

/* SQL编辑器容器 */
.sql-editor-container {
  display: flex;
  flex-direction: column;
  /* 移除固定高度，让编辑器组件自己控制高度 */
  min-height: 60px; /* 允许更小的高度，支持迷你模式 */
}

/* SQL编辑器 */
.sql-editor {
  padding: 16px 20px;
  border-bottom: 1px solid #e4e7ed;
  position: relative;
}

.sql-textarea {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 14px;
}

/* Monaco Editor已经提供了完整的智能提示UI */

/* 查询结果 */
.query-results {
  display: flex;
  flex-direction: column;
  padding: 16px 20px;
  min-height: 300px;
}

.result-content {
  display: flex;
  flex-direction: column;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.result-table {
  margin-bottom: 16px;
}

.result-table .el-table {
  height: auto !important;
}

.result-table .el-table__body-wrapper {
  max-height: none !important;
  height: auto !important;
  overflow: visible !important;
}

.result-table .el-table__body {
  height: auto !important;
}

.result-table .el-table__row {
  height: auto !important;
}

/* 强制显示所有行 */
.result-table .el-table {
  overflow: visible !important;
}

.result-table .el-table .el-table__body-wrapper {
  overflow-y: visible !important;
  max-height: unset !important;
}

.result-footer {
  margin-top: 16px;
  display: flex;
  gap: 16px;
  font-size: 14px;
  color: #606266;
}

.error-content {
  margin-top: 16px;
}

.empty-result {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #909399;
}

.empty-result .el-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.editor-info {
  display: flex;
  gap: 20px;
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
}

.editor-actions {
  display: flex;
  gap: 16px;
  align-items: center;
  padding: 4px 0;
}

/* 新建查询按钮样式 */
.new-query-btn {
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border: 1px solid #d0d7de;
  color: #24292f;
  font-weight: 500;
  font-size: 14px;
  padding: 10px 20px;
  height: 40px;
  min-width: 120px;
  transition: all 0.2s ease;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  border-radius: 6px;
}

.new-query-btn:hover {
  background: linear-gradient(135deg, #f6f8fa 0%, #eaeef2 100%);
  border-color: #8c959f;
  color: #0969da;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.15);
}

.new-query-btn:active {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

/* 执行查询按钮样式增强 */
.execute-query-btn {
  background: linear-gradient(135deg, #1677ff 0%, #0958d9 100%);
  border: none;
  color: white;
  font-weight: 600;
  font-size: 14px;
  padding: 10px 24px;
  height: 40px;
  min-width: 130px;
  transition: all 0.2s ease;
  box-shadow: 0 3px 8px rgba(22, 119, 255, 0.35);
  border-radius: 6px;
}

.execute-query-btn:hover {
  background: linear-gradient(135deg, #4096ff 0%, #1677ff 100%);
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(22, 119, 255, 0.45);
}

.execute-query-btn:active {
  transform: translateY(-1px);
  box-shadow: 0 3px 8px rgba(22, 119, 255, 0.35);
}

.execute-query-btn:disabled {
  background: #f5f5f5;
  color: #bfbfbf;
  border: 1px solid #d9d9d9;
  box-shadow: none;
  transform: none;
}

/* 额外的结果样式 */
.result-header h4 {
  margin: 0;
  color: #303133;
}

.result-actions {
  display: flex;
  gap: 8px;
}

.result-stats {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.result-pagination {
  margin-top: 16px;
  display: flex;
  justify-content: center;
}

.no-results {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #909399;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .left-panel {
    width: 30%;
  }
}

@media (max-width: 768px) {
  .main-content {
    flex-direction: column;
  }

  .left-panel {
    width: 100%;
    height: 300px;
  }

  .right-panel {
    flex: 1;
  }
}

.sql-editor-card {
  margin-bottom: 20px;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.editor-title h3 {
  margin: 0;
  color: #303133;
}

/* 重复的样式已移除，使用上面的统一样式 */

.editor-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.sql-textarea {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 14px;
  line-height: 1.5;
}

.editor-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  background: #f5f7fa;
  border-top: 1px solid #dcdfe6;
}

.editor-info {
  display: flex;
  gap: 20px;
  font-size: 12px;
  color: #909399;
}

.result-card {
  margin-bottom: 20px;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.result-header h3 {
  margin: 0;
  color: #303133;
}

.result-actions {
  display: flex;
  gap: 10px;
}

.result-stats {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.result-table {
  margin-top: 15px;
}

.result-pagination {
  margin-top: 15px;
  display: flex;
  justify-content: center;
}

.empty-result {
  text-align: center;
  padding: 40px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.db-warning {
  color: #e6a23c;
  font-size: 11px;
  margin-left: 8px;
}

.port-hint {
  margin-top: 4px;
  text-align: left;
}

.database-name-hint {
  margin-top: 4px;
  text-align: left;
}

@media (max-width: 768px) {
  .query-sql {
    padding: 10px;
  }

  .database-header {
    flex-direction: column;
    gap: 10px;
    align-items: stretch;
  }

  .database-select {
    flex-direction: column;
    align-items: stretch;
  }

  .result-header {
    flex-direction: column;
    gap: 10px;
    align-items: stretch;
  }

  .result-stats {
    justify-content: center;
  }
}

/* 多结果集样式 */
.multi-results-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.multi-results-header h4 {
  margin: 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
  padding-bottom: 12px;
  border-bottom: 1px solid #e4e7ed;
}

.result-tabs {
  margin-top: 16px;
}

.result-tabs .el-tabs__content {
  padding: 16px;
}

.error-result {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.success-result {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.non-select-result {
  margin: 16px 0;
}

.result-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.table-name {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.sql-preview {
  margin-top: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.sql-preview h5 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #495057;
  font-weight: 600;
}

.sql-preview pre {
  margin: 0;
  padding: 12px;
  background: #ffffff;
  border: 1px solid #dee2e6;
  border-radius: 4px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 13px;
  line-height: 1.4;
  color: #212529;
  white-space: pre-wrap;
  word-wrap: break-word;
  max-height: 200px;
  overflow-y: auto;
}

/* 审核人选择范围提示样式 */
.reviewer-scope-tip {
  margin-bottom: 8px;
}

.reviewer-scope-tip .el-alert {
  border-radius: 4px;
}

.reviewer-scope-tip .el-alert--info {
  background-color: #f4f4f5;
  border-color: #e9e9eb;
}

.reviewer-scope-tip .el-alert--success {
  background-color: #f0f9ff;
  border-color: #c6f6d5;
}

/* SQL权限状态栏样式 */
.sql-status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 16px;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 4px;
  margin-bottom: 8px;
  font-size: 14px;
}

.sql-status-bar.safe {
  background: #f6ffed;
  border-color: #b7eb8f;
}

.sql-status-bar.admin-dangerous {
  background: #fff7e6;
  border-color: #ffd591;
}

.sql-status-bar.forbidden {
  background: #fff2f0;
  border-color: #ffccc7;
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  color: #666;
}

.status-tip {
  padding: 8px 16px;
  background: #fff7e6;
  border: 1px solid #ffd591;
  border-radius: 4px;
  margin-bottom: 8px;
  font-size: 13px;
  color: #d46b08;
}

/* 工单提交按钮样式 */
.submit-workorder-btn {
  background: #fa8c16;
  border-color: #fa8c16;
}

.submit-workorder-btn:hover {
  background: #d46b08;
  border-color: #d46b08;
}
</style>
